Python 中 tkinter 和 tkinter.ttk 的部件之間有什麼區別?
tkinter.ttk 是一個用於為 tkinter 部件設定樣式的模組。就像 CSS 用於設定 HTML 元素的樣式一樣,我們使用 tkinter.ttk 來設定 tkinter 部件的樣式。
以下是tkinter 部件和 tkinter.ttk 之間的主要區別:
Tkinter 部件用於新增按鈕、標籤、文字、捲軸等,但是,與 tkinter 部件相比,tkinter.ttk 支援各種部件。
Tkinter.ttk 不支援 Place、Pack() 和 Grid(),因此建議將 tkinter 部件與 ttk 一起使用。
Ttk 具有許多功能和配置,可以擴充套件原生應用程式的功能,使其外觀更現代。
Tkinter 部件是 tkinter 庫中的原生部件,而 ttk 是一個主題模組。
要覆蓋 tkinter 中的基本 Tk 部件,請使用“from tkinter.ttk import *”。
示例
在以下示例中,我們使用 tkinter.ttk 模組為 tkinter 原生部件設定了樣式。我們將建立一個按鈕,該按鈕將更改文字部件的背景顏色。
#Import the tkinter library from tkinter import * from tkinter.ttk import * #Create an instance of tkinter frame win = Tk() #Set the geometry win.geometry("620x400") #Add a class to style the tkinter widgets style = ttk.Style() style.configure('TEntry', foreground = 'red') #Define a function to change the text color def change_color(): text.configure(background="red") #Create a text widget text=Label(win,text="This is a New Text",foreground="white", background="blue",font=('Aerial bold',20)) text.pack(pady=20) #Create a Button widget Button(win, text= "Click Here", command= change_color).pack(pady=10) win.mainloop()
輸出
執行以上程式碼將產生以下輸出:
現在,點選“點選此處”按鈕。它將文字部件的背景顏色更改為紅色。
廣告