隨着移動設備和雲計算的興起,許多軟件都開始轉向web或移動端,但是桌面應用仍然在很多領域有着不可替代的優勢。Python作為一種簡單易學且功能強大的編程語言,其GUI工具包也讓程序員能夠快速地打造用戶友好的桌面應用。
一、Tkinter:Python自帶的GUI工具包
Tkinter是Python自帶的GUI工具包,簡單易用,可以構建用戶友好的桌面應用。下面是一個簡單的示例:
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("Hello World!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
這個應用包含一個「Hello World」按鈕和一個退出按鈕。代碼中的Application類是繼承自tkinter.Frame的,按鈕控件也是從tkinter.Button來的,當Hello World按鈕被按下時,調用say_hi方法。
二、PyQt:功能強大的GUI庫
PyQt是一個功能強大的GUI庫,可以構建跨平台的桌面應用。下面是一個簡單的示例:
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
from PyQt5.QtCore import pyqtSlot
class App(QWidget):
def __init__(self):
super().__init__()
self.title = 'PyQt5 button - pythonspot.com'
self.left = 10
self.top = 10
self.width = 320
self.height = 200
self.initUI()
def initUI(self):
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
button = QPushButton('PyQt5 button', self)
button.setToolTip('This is an example button')
button.move(100,70)
button.clicked.connect(self.on_click)
self.show()
@pyqtSlot()
def on_click(self):
print('PyQt5 button click')
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = App()
sys.exit(app.exec_())
這個應用包含一個「PyQt5 button」按鈕,點擊後控制台會輸出「PyQt5 button click」的信息。用PyQt建立一個簡單的GUI界面,需要創建窗口(QMainWindow),然後添加控件(QWidget),以及處理控件的事件。
三、Kivy:適用於移動應用開發的GUI框架
Kivy是一個基於Python的GUI框架,適用於移動應用開發。Kivy使用OpenGL ES 2進行呈現,支持多點觸摸輸入,並且可以使用Python,Cython和Lua編寫Kivy應用程序。下面是一個簡單的示例:
from kivy.app import App
from kivy.uix.button import Button
class TestApp(App):
def build(self):
return Button(text='Hello World')
TestApp().run()
這個應用只包含一個「Hello World」按鈕。使用Kivy框架,需要創建一個應用對象,然後根據需要添加控件。
四、結語
Python作為一種功能強大的編程語言,其GUI工具包的簡單易用和跨平台功能是開發桌面應用不可或缺的工具。Tkinter、PyQt和Kivy是開發Python桌面應用的常用GUI工具包,每個框架都有其特殊用途,開發者可以根據需求選擇最適合的工具進行開發。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/309786.html
微信掃一掃
支付寶掃一掃