萬字長文,從 0 到 1 使用 Tkinter 構建 GUI 界面軟件
Tkinter(也叫 Tk 接口)是 Tk 圖形用戶界面工具包標準的 Python 接口。Tk 是一個輕量級的跨平臺圖形用戶界面 (GUI)開發工具。Tk 和 Tkinter 可以運行在大多數 的 Unix 平臺、Windows、和 Macintosh 系統。由于Tkinter是Python自帶的標準庫,我們想要使用它的時候,只需直接導入即可。
一、為什么使用Tkinter庫
Tkinter庫具有以下優點:
- 它是Python的標準GUI庫,無需安裝第三方庫即可使用。
- 它提供了豐富的組件和布局管理器,能夠滿足大多數應用程序的需求。
- 它具有良好的跨平臺性,能夠在多種操作系統上運行。
二、如何使用
在項目中使用Tkinter庫時,只需在代碼開頭導入Tkinter模塊即可。
1import tkinter as tk
打開你的IDE或虛擬環境,執行下面命令,會彈出Tkinter構建的小示例。
1python -m tkinter
三、Tkinter基礎
1. 窗口和組件
在Tkinter中,窗口和組件都是對象。曾做過VC或者Delphi開發的是不是很熟悉。基本上就是Form、Component。各種窗口、組件的屬性、事件、生命周期構成了整個軟件的運行。
我們創建通過tk.Tk()創建一個Form。設置窗口寬(500)、高(300),設置Form的title并啟動。
1import tkinter as tk
2
3# 創建Form
4window = tk.Tk()
5
6# 設置Form屬性
7window.title("用戶登錄")
8window.maxsize(500, 300)
9window.geometry('500x300')
10
11# 創建標簽組件
12label = tk.Label(window, text="Hello, Tkinter!")
13label.pack()
14
15# 創建按鈕組件
16button = tk.Button(window, text="Click me!")
17button.pack()
18# 運行
19window.mainloop()
上面的代碼中,我們首先導入了tkinter模塊,并創建了一個Form對象window。然后,我們創建了一個標簽組件label和一個按鈕組件button,并使用pack()方法將它們添加到窗口中。最后,我們調用窗口對象的mainloop()方法來運行主循環。
2. 布局管理
雖然上面能夠正常運行,但看起來很丑,所以我們也做好組件的布局。在Tkinter中,布局管理器負責管理組件的位置和大小。目前,Tkinter提供了三種布局管理器:pack、grid和place。
- pack布局管理器:按照添加順序將組件放置到窗口中。
- grid布局管理器:將窗口劃分為網格,并將組件放置到指定的網格中。
- place布局管理器:允許開發者精確地控制組件的位置和大小。
下面是grid基于網格布局的登錄窗口:
1import tkinter as tk
2
3
4def login():
5 username = username_entry.get()
6 password = password_entry.get()
7 print(username, password)
8
9
10window = tk.Tk()
11window.title("用戶登錄")
12window.maxsize(300, 200)
13window.geometry('300x200')
14
15tk.Label(window, text="用戶名:").grid(padx=30, pady=30, row=2, column=0)
16username_entry = tk.Entry(window)
17username_entry.grid(row=2, column=1)
18
19# 密碼輸入
20tk.Label(window, text="密碼:").grid(row=4, column=0)
21password_entry = tk.Entry(window, show="*")
22password_entry.grid(row=4, column=1)
23
24# 登錄按鈕
25login_btn = tk.Button(window, text="登錄", command=login)
26login_btn.grid(pady=20, row=8, columnspan=3)
27
28window.mainloop()
上面代碼定義了一個300x200的Form。添加5個組件:2個Label,2個Input框,和一個按鈕Button。每個組件在不同網格中。button按鈕的事件Event是login。
3. 基礎組件說明
以下是 Tkinter 主要組件的列表、簡單示例、常用屬性及事件說明:
(1) Label(標簽)
用途: 顯示文本或圖像 示例: 獲取、失去焦點、綁定事件、顏色變換
1# 鼠標進入時改變背景
2def on_enter(event):
3 label.config(bg="lightgreen", fg="black")
4
5# 鼠標離開時恢復顏色
6def on_leave(event):
7 label.config(bg="white", fg="gray")
8
9# 鼠標點擊事件
10def on_press(event):
11 label.config(bg="lightgreen", fg="black")
12 print('press',event.x,event.y)
13
14window = tk.Tk()
15label = tk.Label(window, text="Hover over me!", bg="white", fg="gray", padx=20, pady=10)
16label.pack(pady=20)
17
18# 綁定事件
19label.bind("<Enter>", on_enter)
20label.bind("<Leave>", on_leave
21label.bind("<Button-1>", on_press)
常用屬性:
- text: 顯示的文字
- bg/background: 背景色
- fg/foreground: 文字顏色
- font: 字體
- image: 顯示圖像(需配合 PhotoImage 使用)
事件:
- Button-1: 鼠標左鍵點擊
- Enter/Leave: 鼠標進入/離開區域
(2) Button(按鈕)
用途: 觸發命令 示例: 按鈕狀態切換,并設置可用、不可用
1# 定義一個bool型變量
2is_enabled = tk.BooleanVar(value=True)
3
4
5# 切換狀態
6def toggle_state():
7 is_enabled.set(not is_enabled.get()) # 切換狀態
8
9
10button = tk.Button(
11 window,
12 text="Toggle State",
13 state=tk.NORMAL if is_enabled.get() else tk.DISABLED,
14 command=toggle_state
15)
16button.pack()
17
18
19# 綁定變量到按鈕狀態
20def update_state(event):
21 button.config(state=tk.NORMAL if is_enabled.get() else tk.DISABLED)
22
23
24update_btn = tk.Button(window, text="Update State")
25update_btn.bind("<Button-1>", update_state)
26update_btn.pack()
常用屬性:
- text: 按鈕文字
- command: 點擊時觸發的函數
- state: 狀態(normal/disabled)
事件:
- Button-1: 鼠標左鍵點擊(可通過 bind 綁定)
(3) Entry(輸入框)
用途: 單行文本輸入,綁定變量輸出, 回車、失去、獲取焦點事件示例:
1# 創建一個 StringVar 變量并綁定到輸入框
2# 創建一個 StringVar 變量并綁定到輸入框
3text_var = tk.StringVar()
4
5
6def update_label():
7 label.config(text=f"輸入內容:{text_var.get()}")
8
9
10def on_return(event):
11 print("用戶按下了回車鍵,輸入內容:", username.get())
12
13
14def on_focus_in(event):
15 password.config(bg="lightyellow") # 獲得焦點時背景變亮黃色
16
17
18def on_focus_out(event):
19 password.config(bg="white") # 失去焦點時恢復白色
20 print(password.get())
21
22
23username = tk.Entry(window, textvariable=text_var)
24username.pack(pady=10)
25
26# 實時顯示輸入框內容的變化
27label = tk.Label(window, text="賬號輸入:")
28label.pack()
29
30label1 = tk.Label(window, text="密碼輸入:")
31label1.pack()
32
33password = tk.Entry(window, show='*')
34password.pack(pady=10)
35
36# 監聽變量變化(需手動觸發)
37username.bind("<KeyRelease>", lambda e: update_label())
38# 綁定回車事件
39username.bind("<Return>", on_return)
40
41# 獲取或失去焦點
42password.bind("<FocusIn>", on_focus_in)
43password.bind("<FocusOut>", on_focus_out)
常用屬性:
- textvariable: 綁定變量(如 StringVar)
- show: 輸入掩碼(如密碼顯示為 *)
事件:
- Return: 按下回車鍵
- FocusIn/FocusOut: 焦點進入/離開
(4) Text(多行文本框)
用途: 多行文本編輯 示例: 插入多行文本,并為key=a的打tag
1def on_key_press(event):
2 # 獲取當前插入點的位置
3 current_index = text.index(tk.INSERT)
4
5 # 獲取按下的鍵
6 key = event.char
7
8 # 如果按下了特定的鍵(例如 'a'),添加一個標記
9 if key == 'a':
10 # 定義一個標記名稱
11 tag_name = "highlight"
12
13 # 添加標記到當前字符位置,-1c為向前移動一個字符
14 text.tag_add(tag_name, current_index + "-1c", current_index)
15
16 # 配置標記的樣式(例如背景顏色)
17 text.tag_config(tag_name, background="yellow", foreground="red")
18
19 # 打印按鍵信息
20 print(f"Key pressed: {key} at position {current_index}")
21
22
23# 創建 Text 組件
24text = tk.Text(window, width=40, height=10)
25text.pack(padx=10, pady=10)
26# 插入光標位置
27text.insert(tk.INSERT, "Hello World")
28# 結尾處插入
29text.insert(tk.END, "Goodbye World")
30# 綁定 <KeyPress> 事件
31text.bind("<KeyPress>", on_key_press)
常用屬性:
- height: 高度(行數)
- width: 寬度(字符數)
事件:
- 按鍵事件
- 支持自定義標記和綁定事件
(5) Frame(框架)
用途: 容器組件,用于分組其他組件 示例: 設置容器及邊緣線和邊框格式
1# 邊緣寬度、邊框格式
2frame = tk.Frame(window, borderwidth=2, relief="groove")
3frame.pack()
4# 按鈕在frame容器內部,可做部署使用
5tk.Button(frame, text="Inside Frame").pack()
(6) Checkbutton(復選框)
用途: 多選項選擇 示例: 選中復選框,然后點擊按鈕
1# 定義一個 Tkinter 變量
2var = tk.StringVar()
3
4# 設置 Checkbutton 的 onvalue 和 offvalue
5checkbutton = tk.Checkbutton(
6 window,
7 text="Select Me",
8 variable=var, # 綁定到變量 var
9 notallow="ON", # 選中時的值
10 offvalue="OFF"# 未選中時的值
11)
12checkbutton.pack(pady=10)
13
14# 添加一個按鈕來顯示當前值
15def show_value():
16 print(f"Checkbutton value: {var.get()}")
17
18
19button = tk.Button(window, text="Show Value", command=show_value)
20button.pack(pady=10)
21
22# 設置 Checkbutton 初始狀態為未選中
23var.set("OFF") # 初始化為 offvalue 的值
屬性:
- variable: 綁定變量(如 IntVar)
- onvalue/offvalue: 選中/未選中的值
(7) Radiobutton(單選按鈕)
用途: 單選選項 示例: 點擊單選按鈕,設置變量var值
1var = tk.StringVar()
2tk.Radiobutton(root, text="Option 1", variable=var, value="1").pack()
3tk.Radiobutton(root, text="Option 2", variable=var, value="2").pack()
(8) Listbox(列表框)
用途: 顯示列表項示例: 獲取選中內容、插入、刪除列表item
1# 創建 Listbox 組件
2listbox = tk.Listbox(window)
3listbox.pack(padx=10, pady=10)
4
5# 插入初始數據
6for item in ["Apple", "Banana", "Cherry", "Date"]:
7 listbox.insert(tk.END, item)
8
9
10# 添加按鈕:選中操作
11def show_selected():
12 selected_indices = listbox.curselection() # 獲取選中的索引
13 if selected_indices:
14 selected_items = [listbox.get(i) for i in selected_indices]
15 print(f"Selected items: {selected_items}")
16 else:
17 print("No item selected.")
18
19
20select_button = tk.Button(window, text="Show Selected", command=show_selected)
21select_button.pack(side=tk.LEFT, padx=5)
22
23
24# 添加按鈕:插入操作
25def insert_item():
26 new_item = entry.get() # 獲取輸入框內容
27 if new_item:
28 listbox.insert(tk.END, new_item)
29 entry.delete(0, tk.END) # 清空輸入框
30
31
32entry = tk.Entry(window)
33entry.pack(side=tk.LEFT, padx=5)
34
35insert_button = tk.Button(window, text="Insert", command=insert_item)
36insert_button.pack(side=tk.LEFT, padx=5)
37
38
39# 添加按鈕:刪除操作
40def delete_item():
41 selected_indices = listbox.curselection()
42 if selected_indices:
43 for index in reversed(selected_indices): # 從后往前刪除,避免索引錯位
44 listbox.delete(index)
45 else:
46 print("No item selected to delete.")
47
48
49delete_button = tk.Button(window, text="Delete", command=delete_item)
50delete_button.pack(side=tk.LEFT, padx=5)
事件:
- ListboxSelect: 選中項改變
(9) Scrollbar(滾動條)
用途: 為其他組件添加滾動功能 示例: 為Text多行文本添加垂直和水平滾動條
1# 設置 wrap=tk.NONE 以允許水平滾動
2text = tk.Text(window,wrap=tk.NONE)
3text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
4
5# 創建垂直滾動條
6vertical_scrollbar = tk.Scrollbar(window, orient=tk.VERTICAL, command=text.yview)
7vertical_scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
8
9# 創建水平滾動條
10horizontal_scrollbar = tk.Scrollbar(window, orient=tk.HORIZONTAL, command=text.xview)
11horizontal_scrollbar.pack(side=tk.BOTTOM, fill=tk.X)
12
13# 配置 Text 小部件以使用滾動條
14text.config(yscrollcommand=vertical_scrollbar.set, xscrollcommand=horizontal_scrollbar.set)
15
16# 添加一些示例文本
17for i in range(50):
18 text.insert(tk.END, f"Line {i + 1}: This is some example text.\n")
(10) Canvas(畫布)
用途: 繪制圖形或自定義界面 示例: 繪制圖形、加載圖片、鼠標點擊生成小黑點
1# 創建 Canvas 小部件
2canvas = tk.Canvas(window, width=400, height=300, bg="white")
3canvas.pack(padx=10, pady=10)
4
5# 繪制一條線
6canvas.create_line(50, 50, 200, 50, fill="blue", width=3)
7
8# 繪制一個矩形
9canvas.create_rectangle(50, 100, 150, 150, outline="green", fill="yellow")
10
11# 繪制一個橢圓
12canvas.create_oval(200, 100, 300, 150, outline="red", fill="pink")
13
14# 繪制一個多邊形
15canvas.create_polygon(350, 100, 375, 150, 325, 150, fill="orange")
16
17# 添加文本
18canvas.create_text(200, 200, text="Hello, Canvas!", fnotallow=("Arial", 16), fill="purple")
19
20# 插入圖像(需要 PIL 庫支持)
21try:
22 from PIL import Image, ImageTk
23
24 # 加載圖像
25 image = Image.open("meinv.jpg") # 替換為你的圖片路徑
26 photo = ImageTk.PhotoImage(image)
27
28 # 在 Canvas 上顯示圖像
29 canvas.create_image(200, 250, image=photo)
30 # 需要保持對圖像的引用,否則會被垃圾回收
31 canvas.image = photo
32except ImportError:
33 print("Pillow library is not installed. Cannot display images.")
34
35
36# 處理鼠標點擊事件
37def on_canvas_click(event):
38 x, y = event.x, event.y
39 print(f"Mouse clicked at: ({x}, {y})")
40 # 在點擊位置繪制一個小圓圈
41 canvas.create_oval(x - 5, y - 5, x + 5, y + 5, fill="black")
42
43
44canvas.bind("<Button-1>", on_canvas_click)
(11) Menu(菜單)
用途: 創建主菜單欄 示例: 創建主菜單,文件、編輯、幫助及各子菜單和彈出消息
1def new_file():
2 messagebox.showinfo("New File", "Create a new file.")
3
4def open_file():
5 messagebox.showinfo("Open File", "Open an existing file.")
6
7def exit_app():
8 if messagebox.askokcancel("Quit", "Do you want to quit?"):
9 window.destroy()
10
11def about():
12 messagebox.showinfo("About", "This is a demonstration of Tkinter Menu widget.")
13
14
15# 創建菜單欄
16menu_bar = tk.Menu(window)
17
18# 添加“文件”菜單
19file_menu = tk.Menu(menu_bar, tearoff=0)
20file_menu.add_command(label="New", command=new_file)
21file_menu.add_command(label="Open", command=open_file)
22file_menu.add_separator()
23file_menu.add_command(label="Exit", command=exit_app)
24menu_bar.add_cascade(label="File", menu=file_menu)
25
26# 添加“編輯”菜單(此處僅作展示,未添加實際功能)
27edit_menu = tk.Menu(menu_bar, tearoff=0)
28edit_menu.add_command(label="Cut")
29edit_menu.add_command(label="Copy")
30edit_menu.add_command(label="Paste")
31menu_bar.add_cascade(label="Edit", menu=edit_menu)
32
33# 添加“幫助”菜單
34help_menu = tk.Menu(menu_bar, tearoff=0)
35help_menu.add_command(label="About", command=about)
36menu_bar.add_cascade(label="Help", menu=help_menu)
37
38# 將菜單欄設置到主窗口
39window.config(menu=menu_bar)
用途: 創建彈出菜單欄 示例: 窗口綁定右鍵 1左鍵 2、滑輪 3、右鍵
1def show_popup(event):
2 # 顯示彈出菜單,指定位置為鼠標點擊的位置
3 popup_menu.post(event.x, event.y)
4
5
6def option1_action():
7 print("Option 1 selected")
8
9
10def option2_action():
11 print("Option 2 selected")
12
13
14def exit_app():
15 if messagebox.askokcancel("Quit", "Do you want to quit?"):
16 window.destroy()
17
18
19# 創建彈出菜單 tearoff=0 禁用菜單分離功能
20popup_menu = tk.Menu(window, tearoff=0)
21popup_menu.add_command(label="Option 1", command=option1_action)
22popup_menu.add_command(label="Option 2", command=option2_action)
23# 添加分隔線
24popup_menu.add_separator()
25popup_menu.add_command(label="Exit", command=exit_app)
26
27# 綁定右鍵點擊事件到主窗口 Button-3 表示鼠標右鍵
28window.bind("<Button-3>", show_popup)
(12) Scale(滑塊)
用途: 通過滑塊選擇數值范圍 示例: RGB顏色取值及16進制顏色碼
1def update_color(*args):
2 """根據 Scale 的值更新背景顏色并輸出十六進制顏色碼"""
3 # 獲取當前 RGB 值
4 red = red_var.get()
5 green = green_var.get()
6 blue = blue_var.get()
7
8 # 生成十六進制顏色碼
9 hex_color = f'#{red:02x}{green:02x}{blue:02x}'
10
11 # 更新 Canvas 背景顏色
12 canvas.config(bg=hex_color)
13
14 # 顯示十六進制顏色碼
15 color_code_label.config(text=f"Hex Color: {hex_color}")
16
17
18# 創建一個 Canvas 用于顯示背景顏色變化
19canvas = tk.Canvas(window, width=300, height=200, bg='#000000')
20canvas.pack(pady=10)
21
22# 創建三個 Scale 小部件分別控制 RGB 顏色通道
23red_var = tk.IntVar()
24red_scale = tk.Scale(window, from_=0, to=255, orient=tk.HORIZONTAL, length=300,
25 variable=red_var, label="Red", command=update_color)
26red_scale.pack(pady=5)
27
28green_var = tk.IntVar()
29green_scale = tk.Scale(window, from_=0, to=255, orient=tk.HORIZONTAL, length=300,
30 variable=green_var, label="Green", command=update_color)
31green_scale.pack(pady=5)
32
33blue_var = tk.IntVar()
34blue_scale = tk.Scale(window, from_=0, to=255, orient=tk.HORIZONTAL, length=300,
35 variable=blue_var, label="Blue", command=update_color)
36blue_scale.pack(pady=5)
37
38# 創建一個標簽用于顯示當前十六進制顏色碼
39color_code_label = tk.Label(window, text="Hex Color: #000000", fnotallow=("Arial", 14))
40color_code_label.pack(pady=10)
41
42# 設置初始值
43red_var.set(0)
44green_var.set(0)
45blue_var.set(0)
(13) Spinbox(數字輸入框)
用途: 數字選擇輸入 示例: 通過數值輸入框進行RGB顏色、輸出十六進制顏色碼
1def update_color():
2 """根據 Spinbox 的值更新背景顏色并輸出十六進制顏色碼"""
3 # 獲取當前 RGB 值
4 red = int(red_spinbox.get())
5 green = int(green_spinbox.get())
6 blue = int(blue_spinbox.get())
7
8 # 生成十六進制顏色碼
9 hex_color = f'#{red:02x}{green:02x}{blue:02x}'
10
11 # 更新 Canvas 背景顏色
12 canvas.config(bg=hex_color)
13
14 # 顯示十六進制顏色碼
15 color_code_label.config(text=f"Hex Color: {hex_color}")
16
17
18# 創建一個 Canvas 用于顯示背景顏色變化
19canvas = tk.Canvas(window, width=300, height=200, bg='#000000')
20canvas.pack(pady=10)
21
22# 創建三個 Spinbox 控制 RGB 顏色通道
23red_label = tk.Label(window, text="Red")
24red_label.pack()
25red_spinbox = tk.Spinbox(window, from_=0, to=255, command=update_color)
26red_spinbox.pack()
27
28green_label = tk.Label(window, text="Green")
29green_label.pack()
30green_spinbox = tk.Spinbox(window, from_=0, to=255, command=update_color)
31green_spinbox.pack()
32
33blue_label = tk.Label(window, text="Blue")
34blue_label.pack()
35blue_spinbox = tk.Spinbox(window, from_=0, to=255, command=update_color)
36blue_spinbox.pack()
37
38# 創建一個標簽用于顯示當前十六進制顏色碼
39color_code_label = tk.Label(window, text="Hex Color: #000000", fnotallow=("Arial", 14))
40color_code_label.pack(pady=10)
41
42# 設置初始值
43red_spinbox.delete(0, tk.END)
44red_spinbox.insert(0, "0")
45green_spinbox.delete(0, tk.END)
46green_spinbox.insert(0, "0")
47blue_spinbox.delete(0, tk.END)
48blue_spinbox.insert(0, "0")
(14) Message(消息框)
用途: 顯示多行文本(自動換行) 示例: 各種消息提示框
1def show_info():
2 messagebox.showinfo(title="信息", message="這是一個信息框")
3
4def show_warning():
5 messagebox.showwarning(title="警告", message="這是一個警告框")
6
7def show_error():
8 messagebox.showerror(title="錯誤", message="這是一個錯誤框")
9
10def ask_question():
11 response = messagebox.askquestion(title="確認", message="你確定要執行此操作嗎?")
12 print(f"用戶選擇了: {response}")
13
14def ask_yes_no():
15 response = messagebox.askyesno(title="是/否", message="請選擇是或否?")
16 print(f"用戶選擇了: {'是' if response else '否'}")
17
18def ask_retry_cancel():
19 response = messagebox.askretrycancel(title="重試/取消", message="操作失敗,是否重試?")
20 print(f"用戶選擇了: {'重試' if response else '取消'}")
21
22def ask_yes_no_cancel():
23 response = messagebox.askyesnocancel(title="是/否/取消", message="請選擇是、否或取消?")
24 if response isTrue:
25 print("用戶選擇了 是")
26 elif response isFalse:
27 print("用戶選擇了 否")
28 else:
29 print("用戶選擇了 取消")
30
31
32# 添加按鈕并綁定函數
33tk.Button(window, text="顯示信息", command=show_info).pack()
34tk.Button(window, text="顯示警告", command=show_warning).pack()
35tk.Button(window, text="顯示錯誤", command=show_error).pack()
36tk.Button(window, text="詢問問題", command=ask_question).pack()
37tk.Button(window, text="是/否", command=ask_yes_no).pack()
38Button(window, text="重試/取消", command=ask_retry_cancel).pack()
39Button(window, text="是/否/取消",command=ask_yes_no_cancel).pack()
(15) Dialog(對話彈窗)
用途: 各種對話框和用戶交互,打開、保存文件、顏色選擇、輸入框示例:
1def open_file_dialog():
2 """打開文件對話框"""
3 filepath = filedialog.askopenfilename(
4 title="選擇一個文件",
5 filetypes=(("文本文件", "*.txt"), ("所有文件", "*.*"))
6 )
7 if filepath:
8 messagebox.showinfo("已選文件", f"你選擇了: {filepath}")
9
10def save_file_dialog():
11 """保存文件對話框"""
12 filepath = filedialog.asksaveasfilename(
13 title="保存文件",
14 defaultextensinotallow=".txt",
15 filetypes=(("文本文件", "*.txt"), ("所有文件", "*.*"))
16 )
17 if filepath:
18 messagebox.showinfo("保存文件", f"文件將被保存為: {filepath}")
19
20def choose_color():
21 """顏色選擇對話框"""
22 color_code = colorchooser.askcolor(title="選擇顏色")
23 if color_code[0] isnotNone:
24 # color_code 返回一個元組 (RGB, HEX)
25 messagebox.showinfo("選擇的顏色", f"你選擇的顏色是: {color_code[1]}")
26
27def prompt_string():
28 """簡單輸入對話框"""
29 user_input = simpledialog.askstring("輸入字符串", "請輸入你的名字:")
30 if user_input:
31 messagebox.showinfo("結果", f"你輸入的名字是: {user_input}")
32 else:
33 messagebox.showwarning("警告", "你沒有輸入任何內容!")
34
35
36
37# 添加按鈕并綁定函數
38tk.Button(window, text="打開文件", command=open_file_dialog).pack(pady=5)
39tk.Button(window, text="保存文件", command=save_file_dialog).pack(pady=5)
40tk.Button(window, text="選擇顏色", command=choose_color).pack(pady=5)
41tk.Button(window, text="輸入字符串", command=prompt_string).pack(pady=5)
四、ttk 擴展組件及其它
除了基礎組件外,Tkinter的 ttk 模塊提供更現代樣式的組件:
- ttk.Combobox: 下拉選擇框
- ttk.Treeview: 樹形列表
- ttk.Progressbar: 進度條
1from tkinter import ttk
2combo = ttk.Combobox(root, values=["A", "B", "C"])
3combo.pack()
五、`Tkinter`不足
- 它的界面設計相對簡陋,不如其他GUI庫(如Qt和wxPython)美觀。
- 它的文檔不夠完善,有時需要查閱第三方資料才能解決問題。
- 它的社區不夠活躍,難以獲得及時的技術支持。
示例:比如Tkinter不支持系統托盤。
1pip install pystray
創建一個Form,當窗口隱藏時,進入系統托盤。點擊托盤彈出菜單:
1def create_tray_icon():
2 """創建系統托盤圖標"""
3 # 創建一個簡單的圖像作為托盤圖標
4 image = Image.open("icon.png") # 替換為你的圖標文件路徑
5 menu = (
6 pystray.MenuItem("顯示窗口", show_window),
7 pystray.MenuItem("退出", quit_app)
8 )
9
10 # 創建托盤圖標
11 icon = pystray.Icon("name", image, "My System Tray App", menu)
12 icon.run()
13
14def show_window():
15 """顯示主窗口"""
16 window.deiconify() # 恢復隱藏的窗口
17
18def hide_window():
19 """隱藏主窗口到系統托盤"""
20 window.withdraw() # 隱藏窗口
21
22def quit_app(icnotallow=None):
23 """退出應用程序"""
24 if icon:
25 icon.stop() # 停止托盤圖標線程
26 window.quit() # 退出 Tkinter 主循環
27
28
29
30# 添加按鈕用于隱藏窗口到托盤
31hide_button = tk.Button(window, text="隱藏到托盤", command=hide_window)
32hide_button.pack(pady=20)
33
34# 啟動系統托盤線程
35tray_thread = Thread(target=create_tray_icon, daemnotallow=True)
36tray_thread.start()
以上就是本文關于Python Tkinter庫入門指南的全部內容。希望本文能夠幫助您快速掌握Tkinter庫的基礎知識,并能夠運用所學知識來創建自己的圖形用戶界面應用程序。