《Python程序设计基础》习题答案与分析 下载本文

第9章 GUI编程

9.1 设计一个窗体,并放置一个按钮,单击按钮后弹出颜色对话框,关闭颜色对话框后提示选中的颜色。

答:Python 2.7.8代码如下,

import wx

class wxGUI(wx.App): def OnInit(self):

frame = wx.Frame(parent=None, title='wxGUI', size=(160,140)) panel = wx.Panel(frame, -1)

buttonOK = wx.Button(panel, -1, 'OK', pos=(0,0))

self.Bind(wx.EVT_BUTTON, self.OnButtonOK, buttonOK)

frame.Show() return True

def OnButtonOK(self, event):

colorDlg = wx.ColourDialog(None) colorDlg.ShowModal()

color = colorDlg.GetColourData().Colour wx.MessageBox(str(color))

app = wxGUI() app.MainLoop()

9.2 设计一个窗体,并放置一个按钮,按钮默认文本为“开始”,单击按钮后文本变为“结束”,再次单击后变为“开始”,循环切换。

答:Python 2.7.8代码如下,

import wx

class wxGUI(wx.App): def OnInit(self):

frame = wx.Frame(parent=None, title='wxGUI', size=(160,140)) panel = wx.Panel(frame, -1)

self.buttonOK = wx.Button(panel, -1, 'Start', pos=(0,0))

self.Bind(wx.EVT_BUTTON, self.OnButtonOK, self.buttonOK)

frame.Show() return True

def OnButtonOK(self, event):

text = self.buttonOK.GetLabelText()

if text == 'Start':

self.buttonOK.SetLabelText('End') elif text == 'End':

self.buttonOK.SetLabelText('Start')

app = wxGUI() app.MainLoop()

9.3 设计一个窗体,模拟QQ登录界面,当用户输入号码123456和密码654321时提示正确,否则提示错误。

答:Python 2.7.8代码如下,

import wx

class wxGUI(wx.App): def OnInit(self):

frame = wx.Frame(parent=None, title='Login', size=(250,150), pos=(350,350)) panel = wx.Panel(frame, -1)

label1 = wx.StaticText(panel, -1, 'UserName:', pos=(0,10), style=wx.ALIGN_RIGHT) label2 = wx.StaticText(panel, -1, 'Password:', pos=(0,30), style=wx.ALIGN_RIGHT)

self.textName = wx.TextCtrl(panel, -1, pos=(70,10), size=(160,20)) self.textPwd = wx.TextCtrl(panel, -1, pos=(70,30), size=(160,20),style=wx.TE_PASSWORD)

buttonOK = wx.Button(panel, -1, 'OK', pos=(30,60))

self.Bind(wx.EVT_BUTTON, self.OnButtonOK, buttonOK) buttonCancel = wx.Button(panel, -1, 'Cancel', pos=(120,60))

self.Bind(wx.EVT_BUTTON, self.OnButtonCancel, buttonCancel) buttonOK.SetDefault()

frame.Show() return True

def OnButtonOK(self, event):

usrName = self.textName.GetValue() usrPwd = self.textPwd.GetValue()

if usrName=='123456' and usrPwd=='654321': wx.MessageBox('Right') else:

wx.MessageBox('Wrong') def OnButtonCancel(self, event): pass app = wxGUI() app.MainLoop()