Python GUI 编程:Tkinter / PyQt / PySimpleGUI 完整对比
Introduction
Python 有多个 GUI 框架。本文对比 Tkinter(内置)、PyQt(功能强大)、PySimpleGUI(最简单)三种方案的用法,讲解主窗口、控件布局、事件绑定、信号槽的核心概念。
---
Tkinter 是 Python 内置 GUI 库,Tkinter GUI 适合小型工具和教学。PyQt 功能最强大适合正式应用,PySimpleGUI 上手最快。
Tkinter 基础
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("我的应用")
root.geometry("400x300")
label = tk.Label(root, text="Hello, Tkinter!", font=("Arial", 20))
label.pack(pady=20)
def on_click():
messagebox.showinfo("提示", "按钮被点击了!")
btn = tk.Button(root, text="点我", command=on_click, bg="#4CAF50", fg="white", padx=20, pady=10)
btn.pack(pady=10)
entry = tk.Entry(root, width=30)
entry.pack(pady=10)
root.mainloop()
PyQt6 完整示例
pip install PyQt6
from PyQt6.QtWidgets import QApplication, QMainWindow, QPushButton, QLabel, QVBoxLayout, QWidget, QLineEdit
from PyQt6.QtCore import pyqtSignal, QObject, Qt
from PyQt6.QtGui import QAction
import sys
class MyWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("PyQt6 示例")
self.setGeometry(100, 100, 400, 300)
# 菜单栏
menubar = self.menuBar()
file_menu = menubar.addMenu("文件")
exit_action = QAction("退出", self)
exit_action.triggered.connect(self.close)
file_menu.addAction(exit_action)
# 中心控件
central = QWidget()
self.setCentralWidget(central)
layout = QVBoxLayout(central)
self.label = QLabel("等待输入...")
self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
layout.addWidget(self.label)
self.input = QLineEdit()
self.input.textChanged.connect(self.on_text_changed)
layout.addWidget(self.input)
btn = QPushButton("确认")
btn.clicked.connect(self.on_click)
layout.addWidget(btn)
def on_text_changed(self, text):
self.label.setText(f"输入了: {text}")
def on_click(self):
self.label.setText(f"最终: {self.input.text()}")
app = QApplication(sys.argv)
window = MyWindow()
window.show()
sys.exit(app.exec())
PySimpleGUI 最简用法
pip install PySimpleGUI
import PySimpleGUI as sg
layout = [
[sg.Text("用户名")],
[sg.Input(key="-USER-")],
[sg.Text("密码")],
[sg.Input(password_char="*", key="-PASS-")],
[sg.Button("登录"), sg.Button("退出")],
]
window = sg.Window("登录", layout)
while True:
event, values = window.read()
if event in (sg.WINDOW_CLOSED, "退出"):
break
if event == "登录":
if values["-USER-"] == "admin" and values["-PASS-"] == "123":
sg.popup("登录成功!")
else:
sg.popup_error("用户名或密码错误")
window.close()
布局管理
# pack 布局(从上到下)
label.pack(fill=tk.BOTH, expand=True, padx=10, pady=5)
# grid 布局(表格)
from tkinter import ttk
ttk.Label(root, text="Name:").grid(row=0, column=0, sticky=tk.E)
ttk.Entry(root).grid(row=0, column=1)
# place 布局(绝对/相对定位)
label.place(x=50, y=100, width=200, height=30)
常见问题
Q1: Tkinter vs PyQt 怎么选?简单工具用 Tkinter,生产级应用用 PyQt,PySimpleGUI 适合快速原型。
Q2: GUI 程序怎么打包成 exe?用 PyInstaller:pyinstaller --onefile --windowed app.py。
Q3: tkinter 不支持中文?设置默认字体:tk.Label(root, text="你好", font=("Microsoft YaHei", 12))。
延伸阅读
- PyQt5 信号与槽机制
- Tkinter 动画和 Canvas 绘图
- Python GUI 美化技巧
---
作者:小马 | 绍大技术网 shaoda.net