Python ttk模塊簡介與使用示例
Python編程之ttk模塊詳細介紹與使用教程
1. ttk 簡介
ttk (Themed Tkinter) 是 Python 標準庫中 tkinter 的一個擴展模塊,提供了更加現(xiàn)代化、主題化的 GUI 組件。與傳統(tǒng)的 tkinter 組件相比,ttk 組件具有以下優(yōu)勢:
- 支持主題切換,外觀更加現(xiàn)代化
- 提供更多高級組件(如進度條、筆記本等)
- 跨平臺一致性更好
- 樣式可定制性更強
2. ttk 基本使用
2.1 導入模塊
import tkinter as tk from tkinter import ttk # 導入ttk模塊
2.2 創(chuàng)建基礎窗口
# 創(chuàng)建主窗口 root = tk.Tk() # 設置窗口標題 root.title("ttk 教程") # 設置窗口大小(寬x高) root.geometry("400x300")
3. ttk 常用組件及示例
3.1 按鈕 (Button)
# 創(chuàng)建ttk按鈕 ttk_button = ttk.Button( root, # 父容器 text="點擊我", # 按鈕顯示文本 command=lambda: print("ttk按鈕被點擊了") # 點擊事件處理函數(shù) ) # 使用pack布局放置按鈕 ttk_button.pack(pady=10) # pady設置垂直方向外邊距
3.2 標簽 (Label)
# 創(chuàng)建ttk標簽 ttk_label = ttk.Label( root, # 父容器 text="這是一個ttk標簽", # 標簽文本 font=("Arial", 12) # 設置字體 ) 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 # 設置寬度 ) 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=["選項1", "選項2", "選項3"], # 下拉選項 state="readonly" # 設置為只讀(不可編輯) ) ttk_combobox.pack(pady=10) ttk_combobox.set("請選擇") # 設置默認顯示文本 # 綁定選擇事件 ttk_combobox.bind("<<ComboboxSelected>>", lambda e: print("選擇了:", ttk_combobox.get()))
3.5 進度條 (Progressbar)
# 創(chuàng)建進度條變量 progress_var = tk.DoubleVar() # 創(chuàng)建ttk進度條 progress = ttk.Progressbar( root, # 父容器 variable=progress_var, # 綁定變量 maximum=100, # 最大值 length=200 # 進度條長度 ) progress.pack(pady=10) # 創(chuàng)建控制進度條的按鈕 start_button = ttk.Button( root, text="開始進度", command=lambda: progress.start(10) # 以10ms間隔開始自動增加 ) start_button.pack(side=tk.LEFT, padx=5) stop_button = ttk.Button( root, text="停止進度", command=progress.stop # 停止自動增加 ) stop_button.pack(side=tk.LEFT, padx=5)
3.6 筆記本 (Notebook)
# 創(chuàng)建ttk筆記本(標簽頁容器) notebook = ttk.Notebook(root) notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 填充整個空間 # 創(chuàng)建第一個標簽頁 frame1 = ttk.Frame(notebook) ttk.Label(frame1, text="這是標簽頁1的內(nèi)容").pack(pady=20) notebook.add(frame1, text="標簽頁1") # 添加標簽頁 # 創(chuàng)建第二個標簽頁 frame2 = ttk.Frame(notebook) ttk.Label(frame2, text="這是標簽頁2的內(nèi)容").pack(pady=20) notebook.add(frame2, text="標簽頁2")
3.7 樹視圖 (Treeview)
# 創(chuàng)建ttk樹視圖 tree = ttk.Treeview(root, columns=("name", "age"), show="headings") # 設置列標題 tree.heading("name", text="姓名") tree.heading("age", text="年齡") # 設置列寬度 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 允許自定義組件樣式,使其更符合應用需求。
4.1 創(chuàng)建樣式對象
# 獲取默認樣式對象 style = ttk.Style() # 查看當前可用主題 print("可用主題:", style.theme_names()) # 設置主題 style.theme_use("clam") # 使用clam主題
4.2 自定義按鈕樣式
# 配置TButton樣式(所有按鈕) style.configure( "TButton", # 樣式名稱 foreground="blue", # 前景色(文字顏色) font=("Arial", 12, "bold"), # 字體 padding=10 # 內(nèi)邊距 ) # 創(chuàng)建自定義樣式的按鈕 custom_button = ttk.Button( root, text="自定義樣式按鈕", style="TButton" # 應用樣式 ) 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="危險操作", style="Danger.TButton" # 應用新樣式 ) danger_button.pack(pady=10)
5. 完整示例應用
下面是一個結合了多個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): """設置自定義樣式""" self.style = ttk.Style() self.style.theme_use("clam") # 配置默認按鈕樣式 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)建筆記本(標簽頁) self.notebook = ttk.Notebook(self.root) self.notebook.pack(fill=tk.BOTH, expand=True, padx=5, pady=5) # 創(chuàng)建第一個標簽頁 - 表單 self.create_form_tab() # 創(chuàng)建第二個標簽頁 - 數(shù)據(jù)展示 self.create_data_tab() def create_form_tab(self): """創(chuàng)建表單標簽頁""" form_frame = ttk.Frame(self.notebook) self.notebook.add(form_frame, text="表單") # 表單標題 ttk.Label( form_frame, text="用戶注冊表單", 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() # 興趣愛好 ttk.Label(form_frame, text="興趣愛好:").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="運動", variable=self.hobbies["sports"]).pack() ttk.Checkbutton(form_frame, text="音樂", 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ù)展示標簽頁""" data_frame = ttk.Frame(self.notebook) self.notebook.add(data_frame, text="數(shù)據(jù)") # 樹視圖 self.tree = ttk.Treeview( data_frame, columns=("name", "age", "department"), show="headings" ) # 設置列 self.tree.heading("name", text="姓名") self.tree.heading("age", text="年齡") self.tree.heading("department", text="部門") # 設置列寬 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ù)到樹視圖""" sample_data = [ ("張三", 28, "技術部"), ("李四", 32, "市場部"), ("王五", 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("警告", "請先選擇要刪除的行") 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("錯誤", "用戶名和密碼不能為空") return message = f""" 注冊信息: 用戶名: {username} 性別: {gender if gender else '未選擇'} 興趣愛好: {', '.join(hobbies) if hobbies else '無'} """ messagebox.showinfo("注冊成功", 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. 總結
ttk 模塊為 Python 的 GUI 開發(fā)提供了更加現(xiàn)代化和靈活的組件,主要特點包括:
- 提供了更多高級組件(如 Combobox、Notebook、Treeview 等)
- 支持主題切換,可以改變整個應用的外觀
- 樣式可定制性強,可以精細控制組件的外觀
- 跨平臺表現(xiàn)一致
通過本教程,你應該已經(jīng)掌握了 ttk 的基本使用方法,包括常用組件的創(chuàng)建、布局、事件綁定以及樣式定制。ttk 與傳統(tǒng)的 tkinter 組件可以混合使用,但為了保持界面一致性,建議盡可能使用 ttk 組件。
在實際開發(fā)中,你可以根據(jù)需求選擇合適的組件,并通過樣式系統(tǒng)來創(chuàng)建符合品牌或設計要求的界面。
到此這篇關于Python ttk模塊簡介與使用示例的文章就介紹到這了,更多相關Python ttk模塊用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
tensorflow 報錯unitialized value的解決方法
今天小編就為大家分享一篇tensorflow 報錯unitialized value的解決方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-02-02python編寫softmax函數(shù)、交叉熵函數(shù)實例
這篇文章主要介紹了python編寫softmax函數(shù)、交叉熵函數(shù)實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-06-06解決Python的str強轉(zhuǎn)int時遇到的問題
下面小編就為大家分享一篇解決Python的str強轉(zhuǎn)int時遇到的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04python基礎教程之基本內(nèi)置數(shù)據(jù)類型介紹
在Python程序中,每個數(shù)據(jù)都是對像,每個對像都有自己的一個類型。不同類型有不同的操作方法,使用內(nèi)置數(shù)據(jù)類型獨有的操作方法,可以更快的完成很多工作2014-02-02