ttkbootstrap实现折叠手风琴面板

import ttkbootstrap as ttk
from ttkbootstrap.constants import *
from ttkbootstrap.style import Bootstyle


class CollapsingFrame(ttk.Frame):
    def __init__(self, master, **kwargs):
        super().__init__(master, padding=10, **kwargs)
        self.columnconfigure(0, weight=1)
        self.cumulative_rows = 0

        self.images = [
            ttk.PhotoImage(file='双上.png'),
            ttk.PhotoImage(file='双右.png')
        ]

    def add(self, child, title="", bootstyle=PRIMARY, **kwargs):
        if child.winfo_class() != "TFrame":
            return

        style_color = Bootstyle.ttkstyle_widget_color(bootstyle)
        frm = ttk.Frame(self, bootstyle=style_color)
        frm.grid(row=self.cumulative_rows, column=0, sticky=EW)

        header = ttk.Label(
            master=frm,
            text=title,
            bootstyle=(style_color, INVERSE)
        )

        if kwargs.get('text-variable'):
            header.configure(textvariable=kwargs.get('text-variable'))
        header.pack(side=LEFT, fill=BOTH, padx=10)

        def _func(c=child):
            return self._toggle_open_closs(c)

        btn = ttk.Button(
            master=frm,
            image=self.images[0],
            bootstyle=style_color,
            command=_func
        )
        btn.pack(side=RIGHT)

        child.btn = btn
        child.grid(row=self.cumulative_rows + 1, column=0, sticky=NSEW)

        self.cumulative_rows += 2

    def _toggle_open_closs(self, child):
        if child.winfo_viewable():
            child.grid_remove()
            child.btn.configure(image=self.images[1])
        else:
            child.grid()
            child.btn.configure(image=self.images[0])


if __name__ == '__main__':
    app = ttk.Window(minsize=(300, 1))
    app.attributes('-topmost', 1)
    app.title("实现折叠手风琴面板ttkbootstrap")
    cf = CollapsingFrame(app)
    cf.pack(fill=BOTH)

    group1 = ttk.Frame(cf, padding=10)
    for x in range(5):
        ttk.Checkbutton(group1, text=f'选项 {x + 1}').pack(fill=X)
    cf.add(child=group1, title="分组1")

    group2 = ttk.Frame(cf, padding=10)
    for x in range(5):
        ttk.Checkbutton(group2, text=f'选项 {x + 1}').pack(fill=X)
    cf.add(child=group2, title="分组2", bootstyle=DANGER)

    group3 = ttk.Frame(cf, padding=10)
    for x in range(5):
        ttk.Checkbutton(group3, text=f'选项 {x + 1}').pack(fill=X)
    cf.add(child=group3, title="分组3", bootstyle=SUCCESS)

    app.mainloop()

 双上图标(放在同一目录):

双左右图标(放在同一目录):

依赖包下载:https://ttkbootstrap.readthedocs.io/en/latest/ 

python -m pip install ttkbootstrap

Github仓库下载:https://github.com/israel-dryer/ttkbootstrap/

python -m pip install git+https://github.com/israel-dryer/ttkbootstrap

Pycharm 2022.2.3

Python 3.10.8

猜你喜欢

转载自blog.csdn.net/PieroPc/article/details/127699890
今日推荐