Ubuntu中Python图形界面如何开发

170
2025/2/28 12:31:58
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu中开发Python图形界面(GUI)有多种选择,以下是一些常用的库和方法:

Tkinter

Tkinter是Python的标准GUI库,适合初学者。它简单易用,无需额外安装,且功能强大。

安装与启动

import tkinter as tk

root = tk.Tk()
root.title("我的第一个GUI应用")
root.geometry("400x300")
root.mainloop()

添加控件

label = tk.Label(root, text="欢迎来到Python GUI世界!")
label.pack()

entry = tk.Entry(root)
entry.pack()

button = tk.Button(root, text="点击我")
button.pack()

PyQt5

PyQt5是一个功能强大的库,支持跨平台运行,适合开发复杂的桌面应用程序。

安装

pip install PyQt5

示例代码

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox

app = QApplication(sys.argv)

window = QWidget()
window.setWindowTitle('我的第一个PyQt窗口')
window.setGeometry(100, 100, 300, 200)
window.show()

def show_message():
    QMessageBox.information(window, '消息', '你点击了按钮!')

button = QPushButton('点击我', window)
button.clicked.connect(show_message)
button.move(100, 80)

sys.exit(app.exec_())

customtkinter

customtkinter是一个用于创建现代、美观GUI的库。

安装

pip install customtkinter

示例代码

import customtkinter as ctk

ctk.set_appearance_mode("dark")
ctk.set_default_color_theme("dark-blue")

root = ctk.CTk()
root.geometry("500x350")
root.title("Login System")

frame = ctk.CTkFrame(master=root)
frame.pack(pady=20, padx=60, fill="both", expand=True)

label = ctk.CTkLabel(master=frame, text="Login System", font=("Roboto", 24))
label.pack(pady=12, padx=10)

entry_username = ctk.CTkEntry(master=frame, placeholder_text="Username")
entry_username.pack(pady=12, padx=10)

entry_password = ctk.CTkEntry(master=frame, placeholder_text="Password", show="*")
entry_password.pack(pady=12, padx=10)

button = ctk.CTkButton(master=frame, text="Login", command=login)
button.pack(pady=12, padx=10)

checkbox = ctk.CTkCheckBox(master=frame, text="Remember Me")
checkbox.pack(pady=12, padx=10)

root.mainloop()

搭建Python开发环境

确保你已经安装了Python和pip。可以使用以下命令安装pip:

sudo apt update
sudo apt install python3-pip

总结

以上是几种在Ubuntu上开发Python图形界面的方法,你可以根据自己的需求选择合适的库进行开发。无论是使用Tkinter进行简单的GUI开发,还是使用PyQt5和customtkinter创建复杂的桌面应用程序,这些库都能提供丰富的控件和功能,帮助你轻松实现图形用户界面。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: Ubuntu与phpstorm兼容性问题