Python实现界面化的方法主要有以下几种:
使用标准库Tkinter
from tkinter import *
def button_click():
print("按钮被点击了!")
root = Tk()
root.title("Tkinter 示例")
button = Button(root, text="点击我", command=button_click)
button.pack()
root.mainloop()
使用PyQt5
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLineEdit
class Example(QWidget):
def __init__(self):
super().__init__()
self.InitUI()
def InitUI(self):
self.setWindowTitle("PyQt5 示例")
vbox = QVBoxLayout()
self.btn = QPushButton("点击我", self)
self.btn.clicked.connect(self.ShowDialog)
vbox.addWidget(self.btn)
self.le = QLineEdit(self)
vbox.addWidget(self.le)
self.setLayout(vbox)
self.setGeometry(300, 300, 300, 200)
self.show()
def ShowDialog(self):
text, ok = QInputDialog.getText(self, "输入对话框", "请输入文本:")
if ok:
print(text)
if __name__ == "__main__":
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
使用wxPython
import wx
class MyFrame(wx.Frame):
def __init__(self, parent, id, title):
wx.Frame.__init__(self, parent, id, title)
self.panel = wx.Panel(self)
self.btn = wx.Button(self.panel, label="点击我", pos=(50, 50))
self.btn.Bind(wx.EVT_BUTTON, self.on_click)
def on_click(self, event):
print("wxPython 按钮被点击了!")
app = wx.App(False)
frame = MyFrame(None, wx.ID_ANY, "wxPython 示例")
frame.Show(True)
app.MainLoop()
选择哪种方法取决于你的具体需求以及你对界面复杂度的预期。Tkinter适合初学者,PyQt5和wxPython提供了更丰富的功能和更灵活的定制选项。