Python中Tkinter?GUI編程詳細教程
前言
Tkinter 是 Python 的標準 GUI 庫,可以快速創(chuàng)建圖形用戶界面。本教程將帶你從基礎開始學習 Tkinter。
1. Tkinter 簡介
Tkinter 是 Python 自帶的 GUI 工具包,基于 Tk GUI 工具集。它的優(yōu)點包括:
- 跨平臺(Windows、macOS、Linux)
- 簡單易學
- 無需額外安裝
2. 第一個 Tkinter 程序
import tkinter as tk
# 創(chuàng)建主窗口
root = tk.Tk()
root.title("我的第一個 Tkinter 程序")
root.geometry("300x200") # 設置窗口大小
# 創(chuàng)建標簽
label = tk.Label(root, text="Hello, Tkinter!")
label.pack() # 將標簽添加到窗口
# 創(chuàng)建按鈕
def on_click():
label.config(text="按鈕被點擊了!")
button = tk.Button(root, text="點擊我", command=on_click)
button.pack()
# 啟動主循環(huán)
root.mainloop()
3. 窗口和基礎組件
3.1 創(chuàng)建窗口
import tkinter as tk
root = tk.Tk()
root.title("窗口標題")
root.geometry("400x300") # 寬度x高度
root.resizable(True, False) # 寬度可調整,高度不可調整
root.iconbitmap("icon.ico") # 設置窗口圖標(僅Windows)
root.configure(bg="lightblue") # 設置背景顏色
3.2 常用組件
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("基礎組件演示")
root.geometry("400x400")
# 1. 標簽
label = tk.Label(root, text="這是一個標簽", font=("Arial", 12), fg="blue")
label.pack(pady=10)
# 2. 按鈕
def button_click():
messagebox.showinfo("提示", "按鈕被點擊了!")
button = tk.Button(root, text="點擊我", command=button_click, bg="lightgreen")
button.pack(pady=10)
# 3. 輸入框
entry = tk.Entry(root, width=30)
entry.insert(0, "默認文本") # 設置默認文本
entry.pack(pady=10)
# 4. 文本框
text = tk.Text(root, height=5, width=30)
text.insert("1.0", "這是一個多行文本框\n可以輸入多行文本")
text.pack(pady=10)
# 5. 復選框
check_var = tk.IntVar()
checkbutton = tk.Checkbutton(root, text="選擇我", variable=check_var)
checkbutton.pack(pady=10)
# 6. 單選框
radio_var = tk.StringVar(value="選項1")
radio1 = tk.Radiobutton(root, text="選項1", variable=radio_var, value="選項1")
radio2 = tk.Radiobutton(root, text="選項2", variable=radio_var, value="選項2")
radio1.pack()
radio2.pack()
root.mainloop()
4. 布局管理
Tkinter 有三種布局管理器:pack、grid 和 place。
4.1 pack 布局
import tkinter as tk
root = tk.Tk()
root.title("pack 布局")
root.geometry("300x200")
# pack 按照添加順序排列組件
tk.Label(root, text="標簽1", bg="red").pack(fill=tk.X, padx=10, pady=5)
tk.Label(root, text="標簽2", bg="green").pack(fill=tk.X, padx=10, pady=5)
tk.Label(root, text="標簽3", bg="blue").pack(fill=tk.X, padx=10, pady=5)
# side 參數(shù)控制方向
tk.Button(root, text="左").pack(side=tk.LEFT, padx=5)
tk.Button(root, text="右").pack(side=tk.RIGHT, padx=5)
tk.Button(root, text="頂部").pack(side=tk.TOP, pady=5)
tk.Button(root, text="底部").pack(side=tk.BOTTOM, pady=5)
root.mainloop()
4.2 grid 布局(最常用)
import tkinter as tk
root = tk.Tk()
root.title("grid 布局")
root.geometry("300x200")
# 使用 grid 布局,類似表格
tk.Label(root, text="用戶名:").grid(row=0, column=0, padx=10, pady=10, sticky=tk.W)
tk.Entry(root).grid(row=0, column=1, padx=10, pady=10)
tk.Label(root, text="密碼:").grid(row=1, column=0, padx=10, pady=10, sticky=tk.W)
tk.Entry(root, show="*").grid(row=1, column=1, padx=10, pady=10)
# 跨列顯示按鈕
tk.Button(root, text="登錄").grid(row=2, column=0, columnspan=2, pady=20, sticky=tk.EW)
# 配置列權重,使第二列可以伸縮
root.grid_columnconfigure(1, weight=1)
root.mainloop()
4.3 place 布局(精確位置)
import tkinter as tk
root = tk.Tk()
root.title("place 布局")
root.geometry("300x200")
# 使用絕對坐標放置組件
tk.Label(root, text="絕對定位", bg="yellow").place(x=50, y=50)
# 使用相對位置
tk.Label(root, text="相對定位", bg="lightblue").place(relx=0.5, rely=0.5, anchor=tk.CENTER)
root.mainloop()
5. 事件處理
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("事件處理")
root.geometry("400x300")
# 1. 按鈕點擊事件
def button_click():
messagebox.showinfo("事件", "按鈕被點擊")
button = tk.Button(root, text="點擊事件", command=button_click)
button.pack(pady=10)
# 2. 鍵盤事件
def on_key_press(event):
print(f"按下了鍵: {event.char}")
label.config(text=f"按下了: {event.char}")
label = tk.Label(root, text="按任意鍵")
label.pack(pady=10)
root.bind("<Key>", on_key_press)
# 3. 鼠標事件
def on_click(event):
print(f"鼠標點擊位置: ({event.x}, {event.y})")
canvas = tk.Canvas(root, width=200, height=100, bg="lightgray")
canvas.pack(pady=10)
canvas.bind("<Button-1>", on_click) # 左鍵點擊
# 4. 輸入框事件
def on_entry_change(event):
print(f"輸入框內容: {entry.get()}")
entry = tk.Entry(root, width=30)
entry.pack(pady=10)
entry.bind("<KeyRelease>", on_entry_change) # 鍵盤釋放時觸發(fā)
root.mainloop()
6. 高級組件
import tkinter as tk
from tkinter import ttk, messagebox, filedialog
root = tk.Tk()
root.title("高級組件")
root.geometry("500x400")
# 1. 下拉菜單
def on_menu_select(event):
messagebox.showinfo("選擇", f"選擇了: {combo.get()}")
combo = ttk.Combobox(root, values=["選項1", "選項2", "選項3"])
combo.set("請選擇")
combo.pack(pady=10)
combo.bind("<<ComboboxSelected>>", on_menu_select)
# 2. 列表框
listbox = tk.Listbox(root, height=4)
for item in ["項目1", "項目2", "項目3", "項目4", "項目5"]:
listbox.insert(tk.END, item)
listbox.pack(pady=10)
def show_selected():
selected = listbox.curselection()
if selected:
messagebox.showinfo("選擇", f"選擇了: {listbox.get(selected[0])}")
tk.Button(root, text="顯示選中項", command=show_selected).pack(pady=5)
# 3. 滾動條
frame = tk.Frame(root)
frame.pack(pady=10)
text = tk.Text(frame, height=5, width=40)
scrollbar = tk.Scrollbar(frame, command=text.yview)
text.configure(yscrollcommand=scrollbar.set)
text.pack(side=tk.LEFT)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 4. 進度條
progress = ttk.Progressbar(root, length=200, mode='indeterminate')
progress.pack(pady=10)
def start_progress():
progress.start(10)
def stop_progress():
progress.stop()
tk.Button(root, text="開始進度", command=start_progress).pack(pady=5)
tk.Button(root, text="停止進度", command=stop_progress).pack(pady=5)
# 5. 文件對話框
def open_file():
filepath = filedialog.askopenfilename(
title="選擇文件",
filetypes=[("文本文件", "*.txt"), ("所有文件", "*.*")]
)
if filepath:
messagebox.showinfo("文件", f"選擇了: {filepath}")
tk.Button(root, text="打開文件", command=open_file).pack(pady=10)
root.mainloop()
7. 綜合示例
創(chuàng)建一個簡單的待辦事項應用:
import tkinter as tk
from tkinter import ttk, messagebox
from datetime import datetime
class TodoApp:
def __init__(self, root):
self.root = root
self.root.title("待辦事項管理")
self.root.geometry("500x400")
self.tasks = []
self.setup_ui()
def setup_ui(self):
# 創(chuàng)建框架
input_frame = tk.Frame(self.root)
input_frame.pack(pady=10, padx=10, fill=tk.X)
# 輸入框和添加按鈕
tk.Label(input_frame, text="新任務:").pack(side=tk.LEFT, padx=(0, 10))
self.task_entry = tk.Entry(input_frame, width=30)
self.task_entry.pack(side=tk.LEFT, padx=(0, 10))
self.task_entry.bind("<Return>", lambda e: self.add_task())
tk.Button(input_frame, text="添加", command=self.add_task, bg="lightgreen").pack(side=tk.LEFT)
# 任務列表
list_frame = tk.Frame(self.root)
list_frame.pack(pady=10, padx=10, fill=tk.BOTH, expand=True)
# 創(chuàng)建樹形視圖顯示任務
columns = ("序號", "任務", "創(chuàng)建時間", "狀態(tài)")
self.tree = ttk.Treeview(list_frame, columns=columns, show="headings", height=10)
for col in columns:
self.tree.heading(col, text=col)
self.tree.column(col, width=100)
self.tree.column("任務", width=200)
# 添加滾動條
scrollbar = ttk.Scrollbar(list_frame, orient=tk.VERTICAL, command=self.tree.yview)
self.tree.configure(yscrollcommand=scrollbar.set)
self.tree.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 操作按鈕
button_frame = tk.Frame(self.root)
button_frame.pack(pady=10)
tk.Button(button_frame, text="標記完成", command=self.complete_task, bg="lightblue").pack(side=tk.LEFT, padx=5)
tk.Button(button_frame, text="刪除任務", command=self.delete_task, bg="lightcoral").pack(side=tk.LEFT, padx=5)
tk.Button(button_frame, text="清空全部", command=self.clear_all, bg="orange").pack(side=tk.LEFT, padx=5)
# 狀態(tài)標簽
self.status_label = tk.Label(self.root, text="總任務數(shù): 0", relief=tk.SUNKEN, anchor=tk.W)
self.status_label.pack(side=tk.BOTTOM, fill=tk.X)
def add_task(self):
task_text = self.task_entry.get().strip()
if task_text:
task_id = len(self.tasks) + 1
create_time = datetime.now().strftime("%H:%M:%S")
self.tasks.append({
"id": task_id,
"text": task_text,
"time": create_time,
"status": "待完成"
})
self.tree.insert("", tk.END, values=(task_id, task_text, create_time, "待完成"))
self.task_entry.delete(0, tk.END)
self.update_status()
else:
messagebox.showwarning("警告", "請輸入任務內容")
def complete_task(self):
selected = self.tree.selection()
if selected:
item = self.tree.item(selected[0])
task_id = item['values'][0]
for task in self.tasks:
if task["id"] == task_id:
task["status"] = "已完成"
break
self.tree.item(selected[0], values=(item['values'][0], item['values'][1], item['values'][2], "已完成"))
self.update_status()
else:
messagebox.showwarning("警告", "請選擇要完成的任務")
def delete_task(self):
selected = self.tree.selection()
if selected:
if messagebox.askyesno("確認", "確定要刪除選中的任務嗎?"):
item = self.tree.item(selected[0])
task_id = item['values'][0]
self.tasks = [task for task in self.tasks if task["id"] != task_id]
self.tree.delete(selected[0])
self.update_status()
else:
messagebox.showwarning("警告", "請選擇要刪除的任務")
def clear_all(self):
if self.tasks and messagebox.askyesno("確認", "確定要清空所有任務嗎?"):
self.tasks.clear()
for item in self.tree.get_children():
self.tree.delete(item)
self.update_status()
def update_status(self):
total = len(self.tasks)
completed = sum(1 for task in self.tasks if task["status"] == "已完成")
self.status_label.config(text=f"總任務數(shù): {total} | 已完成: {completed} | 待完成: {total - completed}")
def main():
root = tk.Tk()
app = TodoApp(root)
root.mainloop()
if __name__ == "__main__":
main()
總結
這個教程涵蓋了 Tkinter 的基礎知識和常用功能:
- 基礎組件:Label、Button、Entry、Text 等
- 布局管理:pack、grid、place 三種布局方式
- 事件處理:鼠標、鍵盤和各種組件事件
- 高級組件:Combobox、Listbox、Progressbar 等
- 綜合應用:創(chuàng)建完整的 GUI 應用程序
通過這個教程,你應該能夠開始使用 Tkinter 創(chuàng)建自己的圖形界面應用程序。繼續(xù)練習的最好方式是嘗試修改示例代碼,添加新功能,或者創(chuàng)建自己的小項目。
到此這篇關于Python中Tkinter GUI編程詳細教程的文章就介紹到這了,更多相關Tkinter GUI編程內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python常見格式化字符串方法小結【百分號與format方法】
這篇文章主要介紹了Python常見格式化字符串方法,結合實例形式分析了百分號方法和format函數(shù)進行字符串格式化的具體使用技巧,需要的朋友可以參考下2016-09-09

