python?tkinter自定義實現(xiàn)Expander控件
和其他成熟的GUI庫相比,tkinter的組件并不是太多,但在自定義組件這一點上,并不遜色于其他框架,接下來就自定義一個Expander控件。
繼承Frame
Expander控件說穿了也很簡單,就是一個長條形的按鈕,按鈕下裝著一個普通的Frame就可以。為了實現(xiàn)這個功能,新建一個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用于初始化控件,上面是一個長條形的按鈕,下面是一個Frame,用于添加新組件。Click是點擊按鈕時的響應函數(shù),目前還沒有完成。
下面稍微演示一下
root = tk.Tk() ex = Expander(root, "expander") ex.pack(side=tk.TOP, fill=tk.BOTH, expand=tk.YES) root.mainloop()
效果如下

點擊事件
接下來就實現(xiàn)Expander的核心功能,點擊按鈕改變內(nèi)容的可見情況。眾所周知,在tkinter中,可以通過pack來把某個控件塞到父控件里。那么如果想把這個控件隱藏,只要將其從父控件中拿出來就可以了,用到的函數(shù)是pack_forget,非常形象。
而內(nèi)容Frame的顯隱,則需要一個標記,記作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,否則就關閉。然后折疊標記取反。
由于新增了一個全局變量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()至此,理論上就實現(xiàn)了一個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)部變量,給暴露出去并不太好,所以最好構造一個Add函數(shù),用來添加新控件,這種東西對于函數(shù)式編程來說可謂手到擒來
def Add(self, Child, **options):
return Child(self.content, **options)然后測試函數(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()
到此這篇關于python tkinter自定義實現(xiàn)Expander控件的文章就介紹到這了,更多相關tkinter自定義Expander控件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
python計算數(shù)字或者數(shù)組的階乘的實現(xiàn)
本文主要介紹了python計算數(shù)字或者數(shù)組的階乘,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-08-08
Python辦公自動化之數(shù)據(jù)可視化與報表生成
在現(xiàn)代辦公環(huán)境中,數(shù)據(jù)處理和報表生成是一項重要的任務,本文將高效介紹如何使用Python進行數(shù)據(jù)可視化和報表生成,讓您的辦公工作更加順利2023-07-07
Django利用cookie保存用戶登錄信息的簡單實現(xiàn)方法
這篇文章主要介紹了Django利用cookie保存用戶登錄信息的簡單實現(xiàn)方法,結合實例形式分析了Django框架使用cookie保存用戶信息的相關操作技巧,需要的朋友可以參考下2019-05-05
Python如何查看兩個數(shù)據(jù)庫的同名表的字段名差異
這篇文章主要介紹了Python如何查看兩個數(shù)據(jù)庫的同名表的字段名差異,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05

