Tkinter 入門指南

Tkinter 是 Python 內置的 GUI(圖形用户界面)庫,無需額外安裝,輕量且易用,適合快速開發小型桌面應用。以下從基礎概念、核心組件、佈局管理、事件處理等方面展開講解,並提供實用示例。


一、基礎框架:創建第一個窗口

import tkinter as tk
from tkinter import ttk  # 導入主題化組件(可選,更美觀)

# 1. 創建主窗口對象
root = tk.Tk()
root.title("我的第一個Tkinter應用")  # 設置窗口標題
root.geometry("400x300")  # 設置窗口大小:寬x高(像素)
root.resizable(False, False)  # 禁止調整窗口大小(寬,高)

# 2. 添加組件(示例:標籤)
label = ttk.Label(root, text="Hello, Tkinter!")
label.pack(pady=20)  # 佈局:垂直方向間距20像素

# 3. 啓動主事件循環(必須)
root.mainloop()

關鍵説明

  • tk.Tk() 創建主窗口,一個程序通常只有一個主窗口
  • mainloop() 是事件循環,負責監聽用户操作(如點擊、輸入)並刷新界面

二、核心組件(常用)

Tkinter 提供多種基礎組件,以下是最常用的類型及示例:

1. 標籤(Label)

用於顯示文本或圖片:

label = ttk.Label(
    root,
    text="這是一個標籤",
    font=("微軟雅黑", 12),  # 字體和大小
    foreground="blue"     # 文字顏色
)
label.pack()

2. 按鈕(Button)

觸發事件(如點擊執行函數):

def on_click():
    label.config(text="按鈕被點擊了!")  # 修改標籤文本

button = ttk.Button(
    root,
    text="點擊我",
    command=on_click  # 綁定點擊事件
)
button.pack(pady=10)

3. 輸入框(Entry)

單行文本輸入:

entry = ttk.Entry(root, width=30)  # width:寬度(字符數)
entry.pack(pady=5)
entry.insert(0, "默認文本")  # 設置默認值

# 獲取輸入內容(通常在按鈕事件中)
def get_input():
    content = entry.get()
    print("輸入內容:", content)

ttk.Button(root, text="獲取輸入", command=get_input).pack()

4. 文本框(Text)

多行文本輸入/顯示:

text = tk.Text(root, width=40, height=5)  # height:行數
text.pack(pady=5)
text.insert("end", "多行文本示例\n第二行內容")  # 插入文本到末尾

# 獲取文本內容
def get_text():
    content = text.get("1.0", "end-1c")  # 1.0:第1行第0列,end-1c:末尾去掉換行符
    print("文本內容:", content)

ttk.Button(root, text="獲取文本", command=get_text).pack()

5. 複選框(Checkbutton)

多選選項:

var1 = tk.StringVar(value="未選中")  # 綁定變量
check = ttk.Checkbutton(
    root,
    text="選項1",
    variable=var1,
    onvalue="選中",
    offvalue="未選中",
    command=lambda: print(var1.get())  # 實時打印狀態
)
check.pack()

6. 單選框(Radiobutton)

單選選項(需綁定同一個變量):

var2 = tk.StringVar()
options = ["選項A", "選項B", "選項C"]
for opt in options:
    ttk.Radiobutton(
        root,
        text=opt,
        variable=var2,
        value=opt,
        command=lambda: print("選中:", var2.get())
    ).pack(anchor="w")  # anchor="w" 左對齊

三、佈局管理

Tkinter 提供 3 種佈局方式,推薦使用 packgrid,避免混用:

1. pack(按方向佈局)

適合簡單佈局,按上下/左右排列:

# 示例:垂直排列
ttk.Button(root, text="按鈕1").pack(side="top", pady=5)  # 頂部
ttk.Button(root, text="按鈕2").pack(side="top", pady=5)
# 水平排列
ttk.Button(root, text="左").pack(side="left", padx=5)
ttk.Button(root, text="右").pack(side="left", padx=5)
  • sidetop/bottom/left/right(默認 top
  • pady/padx:垂直/水平間距
  • fillx(橫向填充)/y(縱向填充)/both
  • expandTrue 表示佔滿剩餘空間

2. grid(網格佈局)

適合複雜佈局,按行/列排列(類似表格):

# 示例:2行2列的網格
ttk.Label(root, text="用户名:").grid(row=0, column=0, padx=5, pady=5, sticky="e")  # sticky="e" 右對齊
ttk.Entry(root).grid(row=0, column=1, padx=5, pady=5)

ttk.Label(root, text="密碼:").grid(row=1, column=0, padx=5, pady=5, sticky="e")
ttk.Entry(root, show="*").grid(row=1, column=1, padx=5, pady=5)  # 密碼隱藏

ttk.Button(root, text="登錄").grid(row=2, column=0, columnspan=2, pady=10)  # 跨2列
  • row/column:行/列索引(從 0 開始)
  • columnspan/rowspan:跨列/跨行
  • sticky:對齊方式(n/s/e/w 或組合,如 ne 右上)

3. place(絕對佈局)

按座標定位(不推薦,窗口縮放後佈局混亂):

ttk.Button(root, text="固定位置").place(x=50, y=50)  # x,y 座標

四、事件處理

除了組件的 command 參數,還可以用 bind 綁定鍵盤/鼠標事件:

1. 綁定鼠標事件

def on_click(event):
    print(f"點擊位置:x={event.x}, y={event.y}")

label = ttk.Label(root, text="點擊我")
label.pack()
label.bind("<Button-1>", on_click)  # <Button-1> 左鍵點擊

常用鼠標事件:

  • <Button-1>:左鍵點擊
  • <Button-3>:右鍵點擊
  • <Double-Button-1>:左鍵雙擊
  • <Motion>:鼠標移動

2. 綁定鍵盤事件

def on_key(event):
    print(f"按下按鍵:{event.keysym}")

root.bind("<Key>", on_key)  # 全局鍵盤事件
entry.bind("<Return>", lambda e: print("回車觸發:", entry.get()))  # 輸入框回車事件

常用鍵盤事件:

  • <Return>:回車鍵
  • <Escape>:ESC 鍵
  • <KeyPress-a>:按下 a 鍵

3. 解除綁定

label.unbind("<Button-1>")  # 解除單個綁定
root.unbind_all("<Key>")    # 解除所有全局鍵盤綁定

五、進階技巧

1. 彈窗(Toplevel)

創建新窗口(子窗口):

def open_new_window():
    top = tk.Toplevel(root)  # 創建子窗口
    top.title("子窗口")
    top.geometry("200x100")
    top.transient(root)  # 子窗口隨主窗口最小化
    ttk.Label(top, text="這是子窗口").pack(pady=20)

ttk.Button(root, text="打開子窗口", command=open_new_window).pack()

2. 消息框(messagebox)

內置提示框(需導入):

from tkinter import messagebox

def show_msg():
    # 信息框
    messagebox.showinfo("提示", "操作成功!")
    # 警告框
    # messagebox.showwarning("警告", "請檢查輸入!")
    # 錯誤框
    # messagebox.showerror("錯誤", "操作失敗!")
    # 確認框
    # result = messagebox.askyesno("確認", "是否刪除?")
    # if result:
    #     print("用户選擇是")

ttk.Button(root, text="顯示消息", command=show_msg).pack()

3. 更改主題(ttk)

ttk 組件支持主題切換:

from tkinter import ttk

# 查看可用主題
print(ttk.Style().theme_names())  # 如:('clam', 'alt', 'default', 'classic')

# 設置主題
style = ttk.Style()
style.theme_use("clam")  # 應用clam主題

六、完整示例:簡易登錄界面

import tkinter as tk
from tkinter import ttk, messagebox

def login():
    username = entry_user.get()
    password = entry_pwd.get()
    if username == "admin" and password == "123456":
        messagebox.showinfo("成功", "登錄成功!")
    else:
        messagebox.showerror("失敗", "用户名或密碼錯誤!")

# 主窗口
root = tk.Tk()
root.title("登錄界面")
root.geometry("300x200")
root.resizable(False, False)

# 網格佈局
ttk.Label(root, text="用户名:").grid(row=0, column=0, padx=10, pady=20, sticky="e")
entry_user = ttk.Entry(root, width=20)
entry_user.grid(row=0, column=1, padx=10, pady=20)

ttk.Label(root, text="密碼:").grid(row=1, column=0, padx=10, pady=5, sticky="e")
entry_pwd = ttk.Entry(root, width=20, show="*")
entry_pwd.grid(row=1, column=1, padx=10, pady=5)

ttk.Button(root, text="登錄", command=login).grid(row=2, column=0, columnspan=2, pady=10)

# 啓動主循環
root.mainloop()

七、常見問題

  1. 中文亂碼:確保代碼文件編碼為 UTF-8,且系統字體支持中文(Tkinter 默認支持)。
  2. 組件不顯示:忘記調用 pack()/grid()/place() 佈局方法。
  3. 主窗口關閉後程序未退出:子窗口需設置 top.destroy()top.protocol("WM_DELETE_WINDOW", top.destroy)
  4. 界面卡頓:耗時操作(如網絡請求)需放在子線程,避免阻塞主事件循環。

Tkinter 適合快速開發小型 GUI 應用,如需更復雜的功能(如美化、高級控件),可考慮擴展庫:

  • tkinter.ttk:內置主題化組件(已集成)
  • customtkinter:現代化 UI 庫(需 pip 安裝:pip install customtkinter
  • PyQt/PySide:功能更強大的 GUI 框架(需額外安裝)