欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

python?tkinter自定義實(shí)現(xiàn)Expander控件

 更新時(shí)間:2023年08月16日 08:42:58   作者:微小冷  
和其他成熟的GUI庫(kù)相比,tkinter的組件并不是太多,但在自定義組件這一點(diǎn)上,并不遜色于其他框架,下面小編就教大家如何自定義一個(gè)Expander控件吧

和其他成熟的GUI庫(kù)相比,tkinter的組件并不是太多,但在自定義組件這一點(diǎn)上,并不遜色于其他框架,接下來就自定義一個(gè)Expander控件。

繼承Frame

Expander控件說穿了也很簡(jiǎn)單,就是一個(gè)長(zhǎng)條形的按鈕,按鈕下裝著一個(gè)普通的Frame就可以。為了實(shí)現(xiàn)這個(gè)功能,新建一個(gè)Frame的子類,像下面這樣

import tkinter as tk
import tkinter.ttk as ttk
class Expander(ttk.Frame):
    def __init__(self, master, title, **options):
        super().__init__(master, **options)
        self.pack()
        self.initWidgets(title)
    def initWidgets(self, title):
        self.btn = ttk.Button(self, text=title, command=self.Click)
        self.btn.pack(side=tk.TOP, fill=tk.X, expand=tk.YES)
        self.content = ttk.Frame(self)
        self.content.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)
    def Click(self):
        pass

其中,initWidgets用于初始化控件,上面是一個(gè)長(zhǎng)條形的按鈕,下面是一個(gè)Frame,用于添加新組件。Click是點(diǎn)擊按鈕時(shí)的響應(yīng)函數(shù),目前還沒有完成。

下面稍微演示一下

root = tk.Tk()
ex = Expander(root, "expander")
ex.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)
root.mainloop()

效果如下

點(diǎn)擊事件

接下來就實(shí)現(xiàn)Expander的核心功能,點(diǎn)擊按鈕改變內(nèi)容的可見情況。眾所周知,在tkinter中,可以通過pack來把某個(gè)控件塞到父控件里。那么如果想把這個(gè)控件隱藏,只要將其從父控件中拿出來就可以了,用到的函數(shù)是pack_forget,非常形象。

而內(nèi)容Frame的顯隱,則需要一個(gè)標(biāo)記,記作self.collapsed,那么Click函數(shù)可以寫為

def Click(self):
    if self.collapsed:
        self.content.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)            
    else:
        self.content.pack_forget()
    self.collapsed = not self.collapsed

即如果已經(jīng)折疊了,那就打開content,否則就關(guān)閉。然后折疊標(biāo)記取反。

由于新增了一個(gè)全局變量self.collapsed,故而需要修改initWidgets函數(shù)

def initWidgets(self, title):
    self.btn = ttk.Button(self, text=title, command=self.Click)
    self.btn.pack(side=tk.TOP, fill=tk.X, expand=tk.YES)
    self.content = ttk.Frame(self)
    self.collapsed = True
    self.Click()

至此,理論上就實(shí)現(xiàn)了一個(gè)Expander,下面演示一下

root = tk.Tk()
ex = Expander(root, "expander")
ex.pack(side=tk.TOP, fill=tk.X)
tk.Label(ex.content, text="Label").pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)
root.mainloop()

需要注意的是,tk.Label的父控件并不是ex,而是ex.content。效果如下

Add函數(shù)

ex.content畢竟是內(nèi)部變量,給暴露出去并不太好,所以最好構(gòu)造一個(gè)Add函數(shù),用來添加新控件,這種東西對(duì)于函數(shù)式編程來說可謂手到擒來

def Add(self, Child, **options):
    return Child(self.content, **options)

然后測(cè)試函數(shù)可寫為

root = tk.Tk()
ex = Expander(root, "expander")
ex.pack(side=tk.TOP, fill=tk.X)
L = ex.Add(tk.Label, text="Label")
L.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES)
root.mainloop()

到此這篇關(guān)于python tkinter自定義實(shí)現(xiàn)Expander控件的文章就介紹到這了,更多相關(guān)tkinter自定義Expander控件內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論