andy 发表于2020-08-28 08:36
读者你好:
请使用书中附带源码
源码如下,与书中源码相比,仅对变量名的全名方式作了点变动,请老师指正:
# -*- coding:utf-8 -*-
import wx # 导入wxPython
class MyFrame(wx.Frame):
def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,title="创建TextCtrl类",size=(400,300))
panel = wx.Panel(self) # 创建画板
# 创建文本和输入框
self.title = wx.StaticText(panel,label="请输入用户名和密码")
self.labelUser = wx.StaticText(panel,label="用户名")
self.textUser = wx.TextCtrl(panel,style=wx.TE_LEFT)
self.labelPwd = wx.StaticText(panel,label="密 码")
self.textPwd = wx.TextCtrl(panel,style=wx.TE_PASSWORD)
# 创建"确定"和"取消"按钮
self.btConfirm = wx.Button(panel,label="确定")
self.btConfirm.Bind(wx.EVT_BUTTON,self.OnclickSubmit)
self.btCancel = wx.Button(panel,label="取消")
self.btCancel.Bind(wx.EVT_BUTTON,self.OnclickCancel)
# 添加容器,容器中控件横向排列
self.hsizerUser = wx.BoxSizer()
self.hsizerUser.Add(self.labelUser,proportion=0,flag=wx.ALL,border=5,userData=None)
self.hsizerUser.Add(self.textUser,proportion=1,flag=wx.ALL,border=5,userData=None)
self.hsizerPwd = wx.BoxSizer()
self.hsizerPwd.Add(self.labelPwd,proportion=0,flag=wx.ALL,border=5,userData=None)
self.hsizerPwd.Add(self.textPwd,proportion=1,flag=wx.ALL,border=5,userData=None)
self.hsizerButton = wx.BoxSizer()
self.hsizerButton.Add(self.btConfirm,proportion=0,flag=wx.ALIGN_CENTER,border=5,userData=None)
self.hsizerButton.Add(self.btCancel,proportion=0,flag=wx.ALIGN_CENTER,border=5,userData=None)
# 添加容器,容器中的控件纵向排列
self.vsizerAll = wx.BoxSizer(wx.VERTICAL)
self.vsizerAll.Add(self.title,proportion=0,flag=wx.BOTTOM|wx.TOP|wx.ALIGN_CENTER,border=15,userData=None)
self.vsizerAll.Add(self.hsizerUser,proportion=0,flag=wx.EXPAND|wx.LEFT|wx.RIGHT,horder=45,userData=None)
self.vsizerAll.Add(self.hsizerPwd,proportion=0,flag=wx.EXPAND|wx.LEFT|wx.RIGHT,horder=45,userData=None)
self.vsizerAll.Add(self.hsizerButton,proportion=0,flag=wx.ALIGN_CENTER|wx.TOP,horder=15,userData=None)
self.panel.SetSizer(self.vsizerAll)
def OnclickSubmit(self,event):
"""单击确定按钮, 执行方法"""
message = ""
userName = self.textUser.GetValue() # 获取输入的用户名
password = self.textPwd.GetValue() # 获取输入的密码
if userName=="" or password=="":
message = "用户名或密码不能为空"
elif userName=="mr" and password=="mrsoft": # 用户名和密码正确
message = "登录成功"
else:
message = "用户名和密码不匹配" # 用户名或密码错误
wx.MessageBox(message) # 弹出提示框
def OnclickCancel(self,event):
""" 单击取消按纽,执行方法 """
self.textUser.SetValue("") # 清空输入的用户名
self.textPwd.SetValue("") # 清空输入的密码
if __name__ == "__main__":
app = wx.App() # 初始化应用
frame = MyFrame(parent=None,id=-1) # 实例MyFrame类,并传递参数
frame.Show() # 显示窗口
app.MainLoop() # 调用MainLoop()主循环方法