如何在 Tkinter 中使用“原生”GUI 介面?


我們通常使用 Tkinter 開發基於標準 GUI 的應用程式,並將預設樣式和主題應用於其中的所有小部件。若要更改應用程式 GUI 的整體樣式,我們使用 ttk 包。Tkinter ttk 是一種主題小部件,用於設定 Tkinter 小部件的樣式。它為小部件提供了一個原生 GUI 介面。

主題小部件具有許多內建功能和特性,可在應用程式中訪問並徹底使用。ttk 的工作原理與 CSS 對 HTML 頁面的工作原理相同。你可以直接透過匯入或透過例項化 ttk 的物件來使用 ttk。一旦建立物件,你就可以定義所有在所有小部件中全域性生效的樣式屬性。

示例

# Import the tkinter library
from tkinter import *
from tkinter import ttk

# Create an instance of tkinter frame
win = Tk()

# Set the size of the Tkinter window
win.geometry("700x350")

# Create an instance of ttk
s = ttk.Style()

# Use the window native theme
s.theme_use('winnative')

# Add a label text
label= Label(win, text="Eat-sleep,Code Repeat", font= ('Aerial 16'), background= "green3")
label.pack(pady = 30)

# Create a ttk styled Button
ttk.Button(win, text = "Button-1").pack()

win.mainloop()

輸出

執行以上程式碼會顯示一個帶有標籤小部件和按鈕的視窗。

更新於: 2021 年 6 月 7 日

493 次瀏覽

開啟您的 職業

透過完成課程獲得認證

現在開始
廣告