pip install,開箱即用。
import sys
import tkinter as tk
def main():
root = tk.Tk()
root.title("Hello Tkinter")
root.minsize(300, 150)
# 標籤
tk.Label(root, text="Hello, Tkinter!", font=("Microsoft YaHei", 16)).pack(pady=20)
# 退出按鈕
tk.Button(root, text="Exit", command=root.destroy,
width=10, font=("Microsoft YaHei", 10)).pack()
root.mainloop()
if __name__ == "__main__":
main()
| 組件 | 用途 | 常用參數 |
|---|---|---|
Tk() | 主窗口(唯一) | title, geometry, minsize, maxsize, resizable |
Label | 顯示文本/圖片 | text, font, fg/bg, image, compound |
Button | 點擊觸發命令 | text, command, width/height, state |
Entry | 單行文本輸入 | textvariable, show='*', validate |
Text | 多行文本編輯 | wrap, undo, font |
Frame | 容器佈局 | padx, pady, borderwidth, relief |
pack() - 線性堆疊
# side: TOP/BOTTOM/LEFT/RIGHT, fill: X/Y/BOTH, expand: True/False
btn1.pack(side=tk.LEFT, padx=5)
btn2.pack(side=tk.LEFT, padx=5)
tk.Label(text="Bottom").pack(side=tk.BOTTOM, fill=tk.X)
grid() - 表格網格(推薦複雜佈局)
tk.Label(text="Name:").grid(row=0, column=0, sticky=tk.E, padx=5, pady=5)
tk.Entry().grid(row=0, column=1, sticky=tk.EW, padx=5, pady=5)
tk.Label(text="Age:").grid(row=1, column=0, sticky=tk.E, padx=5, pady=5)
tk.Entry().grid(row=1, column=1, sticky=tk.EW, padx=5, pady=5)
root.columnconfigure(1, weight=1) # 第 1 列隨窗口拉伸
place() - 絕對/相對定位
# 絕對像素
btn.place(x=100, y=50, width=80, height=30)
# 相對父容器
lbl.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
def on_click():
print("Button clicked!")
btn = tk.Button(text="Click Me", command=on_click)
btn.pack()
# 綁定事件
def on_enter(event):
event.widget['bg'] = 'lightblue'
def on_leave(event):
event.widget['bg'] = 'SystemButtonFace'
btn.bind("", on_enter)
btn.bind("", on_leave)
StringVar / IntVar / BooleanVar
var = tk.StringVar(value="Initial")
entry = tk.Entry(textvariable=var)
label = tk.Label(textvariable=var) # 雙向綁定
entry.pack(); label.pack()
# 監聽變化
def on_change(*_):
print("Value changed to:", var.get())
var.trace_add("write", on_change)
from tkinter import messagebox, filedialog, simpledialog
messagebox.showinfo("Title", "Message")
messagebox.showwarning("Warning", "Be careful!")
messagebox.showerror("Error", "Something went wrong")
if messagebox.askyesno("Confirm", "Delete?"):
print("User said yes")
path = filedialog.askopenfilename(filetypes=[("Text", "*.txt"), ("All", "*.*")])
dir_path = filedialog.askdirectory()
name = simpledialog.askstring("Input", "Your name:")
age = simpledialog.askinteger("Input", "Age:", minvalue=0, maxvalue=150)
root.mainloop() 阻塞直到窗口關閉。
def long_task():
time.sleep(3)
root.after(0, lambda: label.config(text="Done"))
threading.Thread(target=long_task, daemon=True).start()
PhotoImage 需保持引用否則被 GC 導致不顯示。label.image = img。ctypes.windll.shcore.SetProcessDpiAwareness(1)。tk.Tk 或 tk.Frame。python -m tkinter 打開內建示例。ttk 主題控件:from tkinter import ttk,現代外觀、Treeview、Notebook、Combobox。customtkinter (現代風格), tkinterweb (HTML 渲染), pygubu (可視化設計器)。Tkinter 是 Python 內建 GUI 框架的最佳入門選擇。掌握 Tk、三大佈局、事件綁定、變量綁定、對話框,即可構建實用的桌面小工具。進階學習 ttk、MVC 架構、多線程協作,可開發生產級應用。