Python ttk模塊簡(jiǎn)介與使用示例
Python編程之ttk模塊詳細(xì)介紹與使用教程
1. ttk 簡(jiǎn)介
ttk (Themed Tkinter) 是 Python 標(biāo)準(zhǔn)庫(kù)中 tkinter 的一個(gè)擴(kuò)展模塊,提供了更加現(xiàn)代化、主題化的 GUI 組件。與傳統(tǒng)的 tkinter 組件相比,ttk 組件具有以下優(yōu)勢(shì):
- 支持主題切換,外觀更加現(xiàn)代化
- 提供更多高級(jí)組件(如進(jìn)度條、筆記本等)
- 跨平臺(tái)一致性更好
- 樣式可定制性更強(qiáng)
2. ttk 基本使用
2.1 導(dǎo)入模塊
import tkinter as tk from tkinter import ttk # 導(dǎo)入ttk模塊
2.2 創(chuàng)建基礎(chǔ)窗口
# 創(chuàng)建主窗口
root = tk.Tk()
# 設(shè)置窗口標(biāo)題
root.title("ttk 教程")
# 設(shè)置窗口大小(寬x高)
root.geometry("400x300")
3. ttk 常用組件及示例
3.1 按鈕 (Button)
# 創(chuàng)建ttk按鈕
ttk_button = ttk.Button(
root, # 父容器
text="點(diǎn)擊我", # 按鈕顯示文本
command=lambda: print("ttk按鈕被點(diǎn)擊了") # 點(diǎn)擊事件處理函數(shù)
)
# 使用pack布局放置按鈕
ttk_button.pack(pady=10) # pady設(shè)置垂直方向外邊距
3.2 標(biāo)簽 (Label)
# 創(chuàng)建ttk標(biāo)簽
ttk_label = ttk.Label(
root, # 父容器
text="這是一個(gè)ttk標(biāo)簽", # 標(biāo)簽文本
font=("Arial", 12) # 設(shè)置字體
)
ttk_label.pack(pady=10)
3.3 輸入框 (Entry)
# 創(chuàng)建StringVar用于雙向綁定輸入框內(nèi)容
entry_var = tk.StringVar()
# 創(chuàng)建ttk輸入框
ttk_entry = ttk.Entry(
root, # 父容器
textvariable=entry_var, # 綁定變量
width=30 # 設(shè)置寬度
)
ttk_entry.pack(pady=10)
# 創(chuàng)建顯示輸入內(nèi)容的按鈕
show_button = ttk.Button(
root,
text="顯示輸入內(nèi)容",
command=lambda: print("輸入內(nèi)容:", entry_var.get()) # 獲取輸入內(nèi)容
)
show_button.pack(pady=5)3.4 組合框 (Combobox)
# 創(chuàng)建ttk組合框
ttk_combobox = ttk.Combobox(
root, # 父容器
values=["選項(xiàng)1", "選項(xiàng)2", "選項(xiàng)3"], # 下拉選項(xiàng)
state="readonly" # 設(shè)置為只讀(不可編輯)
)
ttk_combobox.pack(pady=10)
ttk_combobox.set("請(qǐng)選擇") # 設(shè)置默認(rèn)顯示文本
# 綁定選擇事件
ttk_combobox.bind("<<ComboboxSelected>>",
lambda e: print("選擇了:", ttk_combobox.get()))3.5 進(jìn)度條 (Progressbar)
# 創(chuàng)建進(jìn)度條變量
progress_var = tk.DoubleVar()
# 創(chuàng)建ttk進(jìn)度條
progress = ttk.Progressbar(
root, # 父容器
variable=progress_var, # 綁定變量
maximum=100, # 最大值
length=200 # 進(jìn)度條長(zhǎng)度
)
progress.pack(pady=10)
# 創(chuàng)建控制進(jìn)度條的按鈕
start_button = ttk.Button(
root,
text="開(kāi)始進(jìn)度",
command=lambda: progress.start(10) # 以10ms間隔開(kāi)始自動(dòng)增加
)
start_button.pack(side=tk.LEFT, padx=5)
stop_button = ttk.Button(
root,
text="停止進(jìn)度",
command=progress.stop # 停止自動(dòng)增加
)
stop_button.pack(side=tk.LEFT, padx=5)3.6 筆記本 (Notebook)
# 創(chuàng)建ttk筆記本(標(biāo)簽頁(yè)容器) notebook = ttk.Notebook(root) notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 填充整個(gè)空間 # 創(chuàng)建第一個(gè)標(biāo)簽頁(yè) frame1 = ttk.Frame(notebook) ttk.Label(frame1, text="這是標(biāo)簽頁(yè)1的內(nèi)容").pack(pady=20) notebook.add(frame1, text="標(biāo)簽頁(yè)1") # 添加標(biāo)簽頁(yè) # 創(chuàng)建第二個(gè)標(biāo)簽頁(yè) frame2 = ttk.Frame(notebook) ttk.Label(frame2, text="這是標(biāo)簽頁(yè)2的內(nèi)容").pack(pady=20) notebook.add(frame2, text="標(biāo)簽頁(yè)2")
3.7 樹(shù)視圖 (Treeview)
# 創(chuàng)建ttk樹(shù)視圖
tree = ttk.Treeview(root, columns=("name", "age"), show="headings")
# 設(shè)置列標(biāo)題
tree.heading("name", text="姓名")
tree.heading("age", text="年齡")
# 設(shè)置列寬度
tree.column("name", width=100)
tree.column("age", width=50)
# 插入數(shù)據(jù)
tree.insert("", tk.END, values=("張三", 25))
tree.insert("", tk.END, values=("李四", 30))
tree.insert("", tk.END, values=("王五", 28))
tree.pack(pady=10)
# 綁定選中事件
tree.bind("<<TreeviewSelect>>",
lambda e: print("選中了:", tree.item(tree.focus())["values"]))4. ttk 樣式定制
ttk 允許自定義組件樣式,使其更符合應(yīng)用需求。
4.1 創(chuàng)建樣式對(duì)象
# 獲取默認(rèn)樣式對(duì)象
style = ttk.Style()
# 查看當(dāng)前可用主題
print("可用主題:", style.theme_names())
# 設(shè)置主題
style.theme_use("clam") # 使用clam主題4.2 自定義按鈕樣式
# 配置TButton樣式(所有按鈕)
style.configure(
"TButton", # 樣式名稱(chēng)
foreground="blue", # 前景色(文字顏色)
font=("Arial", 12, "bold"), # 字體
padding=10 # 內(nèi)邊距
)
# 創(chuàng)建自定義樣式的按鈕
custom_button = ttk.Button(
root,
text="自定義樣式按鈕",
style="TButton" # 應(yīng)用樣式
)
custom_button.pack(pady=10)4.3 創(chuàng)建新樣式
# 定義新樣式 Danger.TButton
style.configure(
"Danger.TButton", # 新樣式名
foreground="red", # 紅色文字
font=("Arial", 12, "bold")
)
# 使用新樣式的按鈕
danger_button = ttk.Button(
root,
text="危險(xiǎn)操作",
style="Danger.TButton" # 應(yīng)用新樣式
)
danger_button.pack(pady=10)5. 完整示例應(yīng)用
下面是一個(gè)結(jié)合了多個(gè)ttk組件的完整示例:
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
class TtkDemoApp:
def __init__(self, root):
self.root = root
self.root.title("ttk 綜合示例")
self.root.geometry("500x500")
# 創(chuàng)建樣式
self.setup_styles()
# 創(chuàng)建界面
self.create_widgets()
def setup_styles(self):
"""設(shè)置自定義樣式"""
self.style = ttk.Style()
self.style.theme_use("clam")
# 配置默認(rèn)按鈕樣式
self.style.configure(
"TButton",
padding=6,
font=("Arial", 10)
)
# 創(chuàng)建成功按鈕樣式
self.style.configure(
"Success.TButton",
foreground="green",
font=("Arial", 10, "bold")
)
def create_widgets(self):
"""創(chuàng)建所有界面組件"""
# 創(chuàng)建筆記本(標(biāo)簽頁(yè))
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# 創(chuàng)建第一個(gè)標(biāo)簽頁(yè) - 表單
self.create_form_tab()
# 創(chuàng)建第二個(gè)標(biāo)簽頁(yè) - 數(shù)據(jù)展示
self.create_data_tab()
def create_form_tab(self):
"""創(chuàng)建表單標(biāo)簽頁(yè)"""
form_frame = ttk.Frame(self.notebook)
self.notebook.add(form_frame, text="表單")
# 表單標(biāo)題
ttk.Label(
form_frame,
text="用戶注冊(cè)表單",
font=("Arial", 14, "bold")
).pack(pady=10)
# 用戶名輸入
ttk.Label(form_frame, text="用戶名:").pack()
self.username = ttk.Entry(form_frame, width=30)
self.username.pack(pady=5)
# 密碼輸入
ttk.Label(form_frame, text="密碼:").pack()
self.password = ttk.Entry(form_frame, width=30, show="*")
self.password.pack(pady=5)
# 性別選擇
ttk.Label(form_frame, text="性別:").pack()
self.gender = tk.StringVar()
ttk.Radiobutton(form_frame, text="男", variable=self.gender, value="male").pack()
ttk.Radiobutton(form_frame, text="女", variable=self.gender, value="female").pack()
# 興趣愛(ài)好
ttk.Label(form_frame, text="興趣愛(ài)好:").pack()
self.hobbies = {
"reading": tk.BooleanVar(),
"sports": tk.BooleanVar(),
"music": tk.BooleanVar()
}
ttk.Checkbutton(form_frame, text="閱讀", variable=self.hobbies["reading"]).pack()
ttk.Checkbutton(form_frame, text="運(yùn)動(dòng)", variable=self.hobbies["sports"]).pack()
ttk.Checkbutton(form_frame, text="音樂(lè)", variable=self.hobbies["music"]).pack()
# 提交按鈕
ttk.Button(
form_frame,
text="提交",
style="Success.TButton",
command=self.submit_form
).pack(pady=20)
def create_data_tab(self):
"""創(chuàng)建數(shù)據(jù)展示標(biāo)簽頁(yè)"""
data_frame = ttk.Frame(self.notebook)
self.notebook.add(data_frame, text="數(shù)據(jù)")
# 樹(shù)視圖
self.tree = ttk.Treeview(
data_frame,
columns=("name", "age", "department"),
show="headings"
)
# 設(shè)置列
self.tree.heading("name", text="姓名")
self.tree.heading("age", text="年齡")
self.tree.heading("department", text="部門(mén)")
# 設(shè)置列寬
self.tree.column("name", width=100)
self.tree.column("age", width=50)
self.tree.column("department", width=150)
self.tree.pack(fill=tk.BOTH, expand=True, padx=5, pady=5)
# 添加一些示例數(shù)據(jù)
self.add_sample_data()
# 添加控制按鈕
control_frame = ttk.Frame(data_frame)
control_frame.pack(pady=5)
ttk.Button(
control_frame,
text="添加數(shù)據(jù)",
command=self.add_data
).pack(side=tk.LEFT, padx=5)
ttk.Button(
control_frame,
text="刪除選中",
command=self.delete_selected
).pack(side=tk.LEFT, padx=5)
def add_sample_data(self):
"""添加示例數(shù)據(jù)到樹(shù)視圖"""
sample_data = [
("張三", 28, "技術(shù)部"),
("李四", 32, "市場(chǎng)部"),
("王五", 25, "人事部")
]
for data in sample_data:
self.tree.insert("", tk.END, values=data)
def add_data(self):
"""添加新數(shù)據(jù)"""
self.tree.insert("", tk.END, values=("新員工", 0, "未分配"))
def delete_selected(self):
"""刪除選中行"""
selected_item = self.tree.selection()
if selected_item:
self.tree.delete(selected_item)
else:
messagebox.showwarning("警告", "請(qǐng)先選擇要?jiǎng)h除的行")
def submit_form(self):
"""處理表單提交"""
username = self.username.get()
password = self.password.get()
gender = self.gender.get()
hobbies = [hobby for hobby, var in self.hobbies.items() if var.get()]
if not username or not password:
messagebox.showerror("錯(cuò)誤", "用戶名和密碼不能為空")
return
message = f"""
注冊(cè)信息:
用戶名: {username}
性別: {gender if gender else '未選擇'}
興趣愛(ài)好: {', '.join(hobbies) if hobbies else '無(wú)'}
"""
messagebox.showinfo("注冊(cè)成功", message)
self.username.delete(0, tk.END)
self.password.delete(0, tk.END)
self.gender.set("")
for var in self.hobbies.values():
var.set(False)
if __name__ == "__main__":
root = tk.Tk()
app = TtkDemoApp(root)
root.mainloop()6. 總結(jié)
ttk 模塊為 Python 的 GUI 開(kāi)發(fā)提供了更加現(xiàn)代化和靈活的組件,主要特點(diǎn)包括:
- 提供了更多高級(jí)組件(如 Combobox、Notebook、Treeview 等)
- 支持主題切換,可以改變整個(gè)應(yīng)用的外觀
- 樣式可定制性強(qiáng),可以精細(xì)控制組件的外觀
- 跨平臺(tái)表現(xiàn)一致
通過(guò)本教程,你應(yīng)該已經(jīng)掌握了 ttk 的基本使用方法,包括常用組件的創(chuàng)建、布局、事件綁定以及樣式定制。ttk 與傳統(tǒng)的 tkinter 組件可以混合使用,但為了保持界面一致性,建議盡可能使用 ttk 組件。
在實(shí)際開(kāi)發(fā)中,你可以根據(jù)需求選擇合適的組件,并通過(guò)樣式系統(tǒng)來(lái)創(chuàng)建符合品牌或設(shè)計(jì)要求的界面。
到此這篇關(guān)于Python ttk模塊簡(jiǎn)介與使用示例的文章就介紹到這了,更多相關(guān)Python ttk模塊用法內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用 setuptools 在 Python 中安裝 egg 
Eggs 是 Python 中以前使用的一種分發(fā)格式,它包含特定項(xiàng)目所需的信息,從依賴(lài)項(xiàng)到環(huán)境變量,在本文中,我們將討論如何在 Python 中安裝 egg 文件,以及可用于實(shí)現(xiàn)此操作的工具,感興趣的朋友一起看看吧2023-08-08
Python使用try except處理程序異常的三種常用方法分析
這篇文章主要介紹了Python使用try except處理程序異常的三種常用方法,結(jié)合實(shí)例形式分析了Python基于try except語(yǔ)句針對(duì)異常的捕獲、查看、回溯等相關(guān)操作技巧,需要的朋友可以參考下2018-09-09
詳解Python的Flask框架中的signals信號(hào)機(jī)制
這里將為大家來(lái)詳解Python的Flask框架中的signals信號(hào)機(jī)制,包括講述信號(hào)的用途,并給出創(chuàng)建信號(hào)、訂閱信號(hào)、發(fā)送信號(hào)的方法,需要的朋友可以參考下2016-06-06
在主機(jī)商的共享服務(wù)器上部署Django站點(diǎn)的方法
這篇文章主要介紹了在主機(jī)商的共享服務(wù)器上部署Django站點(diǎn)的方法,Django是最具人氣的Python框架,需要的朋友可以參考下2015-07-07
Python爬蟲(chóng)獲取國(guó)外大橋排行榜數(shù)據(jù)清單
這篇文章主要介紹了Python爬蟲(chóng)獲取國(guó)外大橋排行榜數(shù)據(jù)清單,文章通過(guò)PyQuery?解析框架展開(kāi)全文詳細(xì)內(nèi)容,需要的小伙伴可以參考一下2022-05-05
Python操控mysql批量插入數(shù)據(jù)的實(shí)現(xiàn)方法
這篇文章主要介紹了Python操控mysql批量插入數(shù)據(jù)的實(shí)現(xiàn)方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10

