Ubuntu中Python GUI編程操作指南
在Ubuntu上開始Python GUI編程前,需先安裝Python環境和必要的工具:
sudo apt update
sudo apt install python3 python3-pip
python3 --version(查看Python版本)和pip3 --version(查看pip版本),確認安裝成功。Python有多種GUI庫,各有優缺點,可根據需求選擇:
Tkinter是Python內置的GUI庫,無需安裝,適合快速入門:
sudo apt install python3-tk安裝。import tkinter as tk
from tkinter import messagebox
def on_click():
messagebox.showinfo("提示", "按鈕被點擊了!")
# 創建主窗口
root = tk.Tk()
root.title("Tkinter示例")
root.geometry("300x200")
# 添加標簽
label = tk.Label(root, text="Hello, Tkinter!", font=("Arial", 14))
label.pack(pady=20)
# 添加按鈕
button = tk.Button(root, text="點擊我", command=on_click)
button.pack()
# 進入主循環
root.mainloop()
保存為tkinter_demo.py,終端運行python3 tkinter_demo.py即可顯示窗口。PyQt5基于Qt框架,提供豐富的控件和信號槽機制,適合復雜應用:
pip3 install PyQt5。import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QPushButton, QVBoxLayout
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
# 設置窗口
self.setWindowTitle("PyQt5示例")
self.setGeometry(100, 100, 300, 200)
# 創建控件
label = QLabel("Hello, PyQt5!", self)
button = QPushButton("點擊我", self)
button.clicked.connect(self.on_click)
# 布局
layout = QVBoxLayout()
layout.addWidget(label)
layout.addWidget(button)
self.setLayout(layout)
def on_click(self):
print("按鈕被點擊了!")
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
保存為pyqt5_demo.py,運行python3 pyqt5_demo.py即可顯示窗口。PyGObject用于開發原生Linux桌面應用,適合GNOME環境:
pip3 install PyGObject。import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
class MainWindow(Gtk.Window):
def __init__(self):
super().__init__(title="PyGObject示例")
self.set_default_size(300, 200)
# 創建按鈕
button = Gtk.Button(label="點擊我")
button.connect("clicked", self.on_click)
# 添加按鈕到窗口
self.add(button)
def on_click(self, widget):
print("按鈕被點擊了!")
win = MainWindow()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()
保存為pygobject_demo.py,運行python3 pygobject_demo.py即可顯示窗口。pack、grid、place,PyQt的QVBoxLayout/QHBoxLayout等布局方式,實現靈活界面。pyinstaller將Python腳本打包為可執行文件(.deb或.AppImage),方便分發:pip3 install pyinstaller
pyinstaller --onefile --windowed your_script.py
python.org文檔、PyQt的riverbankcomputing.com文檔)、在線教程(如Real Python、CSDN)。