第一步:安装wxPython库
在终端输入:
pip install wxpython
第二步:复制下列代码
import wx
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(parent=None, title='用户信息', size=(400, 300))
self.SetMinSize((400, 300))
panel = wx.Panel(self)
my_sizer = wx.BoxSizer(wx.VERTICAL)
# 添加姓名的标签和文本控件
name_sizer = wx.BoxSizer(wx.HORIZONTAL)
name_label = wx.StaticText(panel, label='姓名:')
self.name_ctrl = wx.TextCtrl(panel)
name_sizer.Add(name_label, 1, wx.ALL | wx.EXPAND, 5)
name_sizer.Add(self.name_ctrl, 3, wx.ALL | wx.EXPAND, 5)
# 添加地址的标签和文本控件
address_sizer = wx.BoxSizer(wx.HORIZONTAL)
address_label = wx.StaticText(panel, label='地址:')
self.address_ctrl = wx.TextCtrl(panel)
address_sizer.Add(address_label, 1, wx.ALL | wx.EXPAND, 5)
address_sizer.Add(self.address_ctrl, 3, wx.ALL | wx.EXPAND, 5)
# 添加电子邮件的标签和文本控件
email_sizer = wx.BoxSizer(wx.HORIZONTAL)
email_label = wx.StaticText(panel, label='电子邮件:')
self.email_ctrl = wx.TextCtrl(panel)
email_sizer.Add(email_label, 1, wx.ALL | wx.EXPAND, 5)
email_sizer.Add(self.email_ctrl, 3, wx.ALL | wx.EXPAND, 5)
# 添加提交按钮
submit_btn = wx.Button(panel, label='提交')
submit_btn.Bind(wx.EVT_BUTTON, self.on_submit)
# 将子布局器添加到主布局器
my_sizer.Add(name_sizer, 0, wx.ALL | wx.EXPAND, 5)
my_sizer.Add(address_sizer, 0, wx.ALL | wx.EXPAND, 5)
my_sizer.Add(email_sizer, 0, wx.ALL | wx.EXPAND, 5)
my_sizer.Add(submit_btn, 0, wx.ALL | wx.CENTER, 5)
panel.SetSizer(my_sizer)
self.Centre()
self.Show()
def on_submit(self, event):
name = self.name_ctrl.GetValue()
address = self.address_ctrl.GetValue()
email = self.email_ctrl.GetValue()
# 简单的验证
if not name or not address or not email:
dlg = wx.MessageDialog(self, "请填写所有字段", "错误", wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
else:
# 收集用户信息
info = f'姓名: {name}\n地址: {address}\n电子邮件: {email}'
print(info)
# 提交信息后显示弹窗
dlg = wx.MessageDialog(self, info, "提交信息", wx.OK | wx.ICON_INFORMATION)
dlg.ShowModal()
dlg.Destroy()
# 可选的,提交后清空表单
self.name_ctrl.SetValue('')
self.address_ctrl.SetValue('')
self.email_ctrl.SetValue('')
if __name__ == '__main__':
app = wx.App(False)
frame = MyFrame()
app.MainLoop()
第三步:运行结果
点击运行会弹出
输入信息,会弹出输入结果的窗口,运行窗口也会输出文本