Debian 上使用 Python 创建图形界面的完整指南
一 环境准备
- 更新系统并安装基础工具:
- sudo apt update
- sudo apt install python3 python3-pip
- 建议使用虚拟环境隔离依赖:
- python3 -m venv venv
- source venv/bin/activate
- 按需安装 GUI 依赖(见下表),随后即可在虚拟环境中使用 pip 安装对应 Python 包。
二 常用方案与安装命令
| 方案 |
适用场景 |
Debian 系统依赖 |
Python 安装 |
备注 |
| Tkinter |
入门、小型工具 |
sudo apt install python3-tk |
内置无需安装 |
轻量、跨平台 |
| PyQt5 / PySide6 |
专业级桌面、复杂界面 |
无(pip 安装) |
pip install PyQt5 PyQt5-tools 或 pip install PySide6 |
Qt 生态、功能丰富 |
| PyGObject(GTK) |
原生 GNOME 风格 |
sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0 |
无需额外 pip |
Linux 原生外观 |
| wxPython |
原生外观跨平台 |
sudo apt install python3-wxgtk4.0 |
pip install wxPython |
桌面工具类应用 |
| Kivy |
触摸/移动与跨平台 |
无(pip 安装) |
pip install kivy |
支持 Android/iOS |
| customtkinter |
现代化 Tkinter 界面 |
无(pip 安装) |
pip install customtkinter |
主题、圆角等现代控件 |
| 以上方案在 Debian 上均可用,选择时优先考虑项目复杂度、外观需求与发布平台。 |
|
|
|
|
三 快速上手示例
- Tkinter 最小示例
- sudo apt install python3-tk
- 代码示例:
- import tkinter as tk
root = tk.Tk(); root.title(“Tkinter”)
tk.Label(root, text=“Hello, Tkinter”).pack(pady=20)
tk.Button(root, text=“点击”, command=lambda: print(“clicked”)).pack()
root.mainloop()
- PyQt5 最小示例
- pip install PyQt5
- 代码示例:
- from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout
app = QApplication([])
w = QWidget(); w.setWindowTitle(“PyQt5”)
lay = QVBoxLayout(); w.setLayout(lay)
lbl = QLabel(“Hello, PyQt5”); btn = QPushButton(“点击”)
lay.addWidget(lbl); lay.addWidget(btn)
btn.clicked.connect(lambda: lbl.setText(“clicked”))
w.show(); app.exec_()
- PyGObject(GTK)最小示例
- sudo apt install python3-gi python3-gi-cairo gir1.2-gtk-3.0
- 代码示例:
- import gi; gi.require_version(‘Gtk’, ‘3.0’)
from gi.repository import Gtk
win = Gtk.Window(title=“GTK”); win.connect(“destroy”, Gtk.main_quit)
btn = Gtk.Button(label=“点击”); btn.connect(“clicked”, lambda w: print(“clicked”))
win.add(btn); win.show_all(); Gtk.main()
- 使用 Qt Designer(PyQt5)
- pip install PyQt5 PyQt5-tools
- 启动 designer 设计界面,保存为 .ui;使用 pyuic5 转换:pyuic5 my.ui -o ui_main.py
- 在代码中继承生成的界面类并连接信号槽。
四 进阶与发布
- 布局与事件
- Tkinter:布局用 pack/grid/place;事件用 command 或 bind。
- PyQt:布局用 QVBoxLayout/QHBoxLayout;事件用信号槽(clicked.connect)。
- 打包发布
- 使用 PyInstaller 将脚本打包为可执行文件:pip install pyinstaller;pyinstaller --onefile app.py(可加 --windowed 隐藏控制台)。
- 选择建议
- 初学者/小工具:优先 Tkinter;需要更好观感可试 customtkinter。
- 企业级与复杂界面:选 PyQt5/PySide6(Qt 生态完备)。
- Linux 原生外观:选 PyGObject(GTK) 或 wxPython。
- 触摸/移动与跨端:选 Kivy。