wxpython入门(五)窗体和对话框

wxpython入门(五)窗体和对话框

参考书籍
http://wiki.woodpecker.org.cn/moin/WxPythonInAction

第八章 将构建放入窗体中
wx.Frame框架和panel 面板
一个简单的框架,examples:

import wx

if __name__ == '__main__':
app = wx.PySimpleApp()
frame = wx.Frame(None,-1,"A Frame",style=wx.DEFAULT_FRAME_STYLE,size=(200, 100))
frame.Show()
app.MainLoop()

wx.Frame的构造函数:
wx.Frame(parent, id=-1, title="", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,name="frame")

展示了wx.Frame子类,examples:

import wx

class SubclassFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,'Frame Subclass',size=(300, 100))
panel = wx.Panel(self,-1)
button = wx.Button(panel,-1,"Close Me",pos=(15,15))
self.Bind(wx.EVT_BUTTON, self.OnCloseMe, button)
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow)

def OnCloseMe(self, event):
self.Close(True)

def OnCloseWindow(self, event):
self.Destroy()

if __name__ == '__main__':
app = wx.PySimpleApp()
SubclassFrame().Show()
app.MainLoop()

添加带样式的框架,examples:
import wx
class HelpFrame(wx.Frame):
def __init__(self):
pre = wx.PreFrame() #1 预构建对象
pre.SetExtraStyle(wx.FRAME_EX_CONTEXTHELP)
pre.Create(None, -1, "Help Context", size=(300, 100),
style=wx.DEFAULT_FRAME_STYLE^(wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX)) #2 创建框架
self.PostCreate(pre) #3 底层C++指针的传递
if __name__ == '__main__':
app = wx.PySimpleApp()
HelpFrame().Show()
app.MainLoop()

带滚动条的框架
wx.ScrolledWindow,examples:

import wx

class ScrollbarFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self,None,-1,'ScrollbarExample',size=(300, 200))
self.scroll = wx.ScrolledWindow(self,-1)
self.scroll.SetScrollbars(1, 1, 600, 400)
self.button = wx.Button(self.scroll,-1,"ScrollMe",pos=(50,20))
self.Bind(wx.EVT_BUTTON, self.OnClickTop, self.button)
self.button2 = wx.Button(self.scroll,-1,"ScrollBack",pos=(500,350))
self.Bind(wx.EVT_BUTTON, self.OnClickBottom, self.button2)
def OnClickTop(self, event):
self.scroll.Scroll(600, 400)
def OnClickBottom(self, event):
self.scroll.Scroll(1, 1)

if __name__ == '__main__':
app = wx.PySimpleApp()
frame = ScrollbarFrame()
frame.Show()
app.MainLoop()

wx.ScrolledWindow的构造函数几乎与wx.Panel的相同:
wx.ScrolledWindow(parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.HSCROLL | wx.VSCROLL,name="scrolledWindow")

指定滚动区域的尺寸
SetScrollbars(pixelsPerUnitX, pixelsPerUnitY, noUnitsX, noUnitsY,xPos=0, yPos=0, noRefresh=False)

多文档框架
wx.MDIParentFrame,examples:

import wx

class MDIFrame(wx.MDIParentFrame):
def __init__(self):
wx.MDIParentFrame.__init__(self,None,-1,"MDIParent",size=(600,400))
menu = wx.Menu()
menu.Append(5000,"Window")
menu.Append(5001, "Exit")
menubar = wx.MenuBar()
menubar.Append(menu, "menu1")
self.SetMenuBar(menubar)
self.Bind(wx.EVT_MENU, self.OnNewWindow, id=5000)
self.Bind(wx.EVT_MENU, self.OnExit, id=5001)
def OnExit(self, evt):
self.Close(True)
def OnNewWindow(self, evt):
win = wx.MDIChildFrame(self, -1, "Child Window")
win.Show(True)
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = MDIFrame()
frame.Show()
app.MainLoop()

wx.MDIParentFrame的构造函数:
wx.MDIParentFrame(parent, id, title, pos = wx.DefaultPosition, size=wxDefaultSize,
style=wx.DEFAULT_FRAME_STYLE | wx.VSCROLL | wx.HSCROLL, name="frame")

小型框架
wx.MiniFrame,examples:

import wx

class MiniFrame(wx.MiniFrame):
def __init__(self):
wx.MiniFrame.__init__(self,None,-1,'MiniFrame',size=(300, 100))
panel = wx.Panel(self, -1, size=(300, 100))
button = wx.Button(panel, -1, "CloseMe", pos=(15, 15))
self.Bind(wx.EVT_BUTTON,self.OnCloseMe,button)
self.Bind(wx.EVT_CLOSE,self.OnCloseWindow)
def OnCloseMe(self, event):
self.Close(True)
def OnCloseWindow(self, event):
self.Destroy()
if __name__ == '__main__':
app = wx.PySimpleApp()
MiniFrame().Show()
app.MainLoop()

wx.MiniFrame的构造函数等同于wx.Frame

非矩形框架
暂时略过

分隔窗
暂时略过

第九章 通过对话框让用户选择

模式对话框
wx.Dialog,examples:

import wx

class SubclassDialog(wx.Dialog):
def __init__(self):#初始化对话框
wx.Dialog.__init__(self,None,-1,'DialogSubclass',size=(300, 100))
okButton = wx.Button(self,wx.ID_OK,"OK",pos=(15,15))
okButton.SetDefault()
cancelButton = wx.Button(self,wx.ID_CANCEL,"Cancel",pos=(115, 15))

if __name__ == '__main__':
app = wx.PySimpleApp()
app.MainLoop()
dialog = SubclassDialog()
result = dialog.ShowModal()#显示模式对话框
if result == wx.ID_OK:
print "OK"
else:
print "Cancel"
dialog.Destroy()

消息框
wx.MessageDialog,examples:
import wx

if __name__ == "__main__":
app = wx.PySimpleApp()
dlg = wx.MessageDialog(None, "Is this explanation OK?",'A Message Box',
wx.YES_NO | wx.ICON_QUESTION)
retCode = dlg.ShowModal()
if (retCode == wx.ID_YES):
print "yes"
else:
print "no"
dlg.Destroy()

wx.MessageDialog的构造函数:
wx.MessageDialog(parent, message, caption="Message box",style=wx.OK | wx.CANCEL, pos=wx.DefaultPosition)

文本输入对话框
wx.TextEntryDialog,examples:
import wx
if __name__ == "__main__":
app = wx.PySimpleApp()
dialog = wx.TextEntryDialog(None,
"What kind of text would you like to enter?",
"Text Entry", "Default Value", style=wx.OK|wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
print "You entered: %s" % dialog.GetValue()
dialog.Destroy()

对话框显示选项列表
wx.SingleChoiceDialog,examples:

import wx

if __name__ == "__main__":
app = wx.PySimpleApp()
choices = ["Alpha", "Baker", "Charlie", "Delta"]
dialog = wx.SingleChoiceDialog(None,"PickAWord","Choices",choices)
if dialog.ShowModal() == wx.ID_OK:
print "You selected: %s\n" % dialog.GetStringSelection()
dialog.Destroy()

wx.SingleChoiceDialog的构造函数:
wx.SingleChoiceDialog(parent, message, caption, choices,
clientData=None, style=wx.OK | wx.CANCEL | wx.CENTRE, pos=wx.DefaultPosition)

进度条对话框
wx.ProgressDialog,examples:
import wx

if __name__ == "__main__":
app = wx.PySimpleApp()
progressMax = 10
dialog = wx.ProgressDialog("A progress box", "Time remaining", progressMax,
style=wx.PD_CAN_ABORT | wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME)
keepGoing = True
count = 0
while keepGoing and count < progressMax:
count = count + 1
wx.Sleep(1)
keepGoing = dialog.Update(count)
dialog.Destroy()

构造函数:
wx.ProgressDialog(title, message, maximum=100, parent=None, style=wx.PD_AUTO_HIDE | wx.PD_APP_MODAL)

文件选择对话框
wx.FileDialog,examples:
import wx
import os

if __name__ == "__main__":
app = wx.PySimpleApp()
wildcard = "Python source (*.py)|*.py|" \
"Compiled Python (*.pyc)|*.pyc|" \
"All files (*.*)|*.*"
dialog = wx.FileDialog(None,"ChooseAfile",os.getcwd(),"",wildcard,wx.OPEN)
if dialog.ShowModal() == wx.ID_OK:
print dialog.GetPath()

dialog.Destroy()

构造函数:
wx.FileDialog(parent, message="Choose a file", defaultDir="",
defaultFile="", wildcard="*.*", style=0, pos=wx.DefaultPosition)

目录对话框
wx.DirDialog,examples:

import wx

if __name__ == "__main__":
app = wx.PySimpleApp()
dialog = wx.DirDialog(None,"ChooseAdirectory:",
style=wx.DD_DEFAULT_STYLE|wx.DD_NEW_DIR_BUTTON)
if dialog.ShowModal() == wx.ID_OK:
print dialog.GetPath()
dialog.Destroy()

构造函数:
wx.DirDialog(parent, message="Choose a directory", defaultPath="",
style=0, pos = wx.DefaultPosition, size = wx.DefaultSize, name="wxDirCtrl")

字体选择对话框
wx.FontDialog,examples:

import wx

if __name__ == "__main__":
app = wx.PySimpleApp()
dialog = wx.FontDialog(None, wx.FontData())
if dialog.ShowModal() == wx.ID_OK:
data = dialog.GetFontData()
font = data.GetChosenFont()
colour = data.GetColour()
print 'You selected: "%s", %d points\n' % (
font.GetFaceName(), font.GetPointSize())
dialog.Destroy()

wx.FontDialog 的构造函数:
wx.FontDialog(parent, data)

颜色选择对话框
wx.ColourDialog,examples:
import wx

if __name__ == "__main__":
app = wx.PySimpleApp()
dialog = wx.ColourDialog(None)
dialog.GetColourData().SetChooseFull(True)
if dialog.ShowModal() == wx.ID_OK:
data = dialog.GetColourData()
print 'You selected: %s\n' % str(data.GetColour().Get())
dialog.Destroy()

构造函数:
wx.ColourDialog(parent, data=None)

图片浏览对话框
wx.lib.imagebrowser.ImageDialog,examples:
import wx
import wx.lib.imagebrowser as imagebrowser

if __name__ == "__main__":
app = wx.PySimpleApp()
dialog = imagebrowser.ImageDialog(None)
if dialog.ShowModal() == wx.ID_OK:
print "You Selected File: " + dialog.GetFile()
dialog.Destroy()

构造函数:
ImageDialog(parent, set_dir=None)

创建向导对话框
wx.wizard.WizardPageSimple,examples:

import wx
import wx.wizard
class TitledPage(wx.wizard.WizardPageSimple):#1 创建页面样板
def __init__(self, parent, title):
wx.wizard.WizardPageSimple.__init__(self, parent)
self.sizer = wx.BoxSizer(wx.VERTICAL)
self.SetSizer(self.sizer)
titleText = wx.StaticText(self, -1, title)
titleText.SetFont(wx.Font(18,wx.SWISS,wx.NORMAL,wx.BOLD))
self.sizer.Add(titleText, 0,wx.ALIGN_CENTRE | wx.ALL, 5)
self.sizer.Add(wx.StaticLine(self,-1),0,wx.EXPAND|wx.ALL,5)

if __name__ == "__main__":
app = wx.PySimpleApp()
wizard = wx.wizard.Wizard(None, -1, "Simple Wizard")# 创建向导实例
# 创建向导页面
page1 = TitledPage(wizard, "Page 1")
page2 = TitledPage(wizard, "Page 2")
page3 = TitledPage(wizard, "Page 3")
page4 = TitledPage(wizard, "Page 4")
page1.sizer.Add(wx.StaticText(page1,-1,"Testing the wizard"))
page4.sizer.Add(wx.StaticText(page4,-1,"This is the last page."))
#2 创建页面链接
wx.wizard.WizardPageSimple_Chain(page1, page2)
wx.wizard.WizardPageSimple_Chain(page2, page3)
wx.wizard.WizardPageSimple_Chain(page3, page4)
wizard.FitToPage(page1)#3 调整向导的尺寸
if wizard.RunWizard(page1):#4 运行向导
print "Success"
wizard.Destroy()

构造函数:
wx.wizard.Wizard(parent, id=-1, title=wx.EmptyString, bitmap=wx.NullBitmap, pos=wx.DefaultPosition)

启动提示对话框
wx.CreateFileTipProvider,examples:
import wx

if __name__ == "__main__":
app = wx.PySimpleApp()
provider = wx.CreateFileTipProvider("tips.txt", 0)
wx.ShowTip(None, provider, True)

构造函数:
wx.CreateFileTipProvider(filename, currentTip)

验证器的使用
examples:

import wx
about_txt = """\
The validator used in this example will ensure that the text
controls are not empty when you press the Ok button, and
will not let you leave if any of the Validations fail."""
class NotEmptyValidator(wx.PyValidator):# 创建验证器子类
def __init__(self):
wx.PyValidator.__init__(self)
def Clone(self):
"""
Note that every validator must implement the Clone() method.
"""
return NotEmptyValidator()
def Validate(self, win):#1 使用验证器方法
textCtrl = self.GetWindow()
text = textCtrl.GetValue()
if len(text) == 0:
wx.MessageBox("This field must contain some text!", "Error")
textCtrl.SetBackgroundColour("pink")
textCtrl.SetFocus()
textCtrl.Refresh()
return False
else:
textCtrl.SetBackgroundColour(wx.SystemSettings_GetColour(wx.SYS_COLOUR_WINDOW))
textCtrl.Refresh()
return True
def TransferToWindow(self):
return True
def TransferFromWindow(self):
return True
class MyDialog(wx.Dialog):
def __init__(self):
wx.Dialog.__init__(self, None, -1, "Validators: validating")
# Create the text controls
about = wx.StaticText(self, -1, about_txt)
name_l = wx.StaticText(self, -1, "Name:")
email_l = wx.StaticText(self, -1, "Email:")
phone_l = wx.StaticText(self, -1, "Phone:")
#2 使用验证器
name_t = wx.TextCtrl(self, validator=NotEmptyValidator())
email_t = wx.TextCtrl(self, validator=NotEmptyValidator())
phone_t = wx.TextCtrl(self, validator=NotEmptyValidator())
# Use standard button IDs
okay = wx.Button(self, wx.ID_OK)
okay.SetDefault()
cancel = wx.Button(self, wx.ID_CANCEL)
# Layout with sizers
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(about, 0, wx.ALL, 5)
sizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5)
fgs = wx.FlexGridSizer(3, 2, 5, 5)
fgs.Add(name_l, 0, wx.ALIGN_RIGHT)
fgs.Add(name_t, 0, wx.EXPAND)
fgs.Add(email_l, 0, wx.ALIGN_RIGHT)
fgs.Add(email_t, 0, wx.EXPAND)
fgs.Add(phone_l, 0, wx.ALIGN_RIGHT)
fgs.Add(phone_t, 0, wx.EXPAND)
fgs.AddGrowableCol(1)
sizer.Add(fgs, 0, wx.EXPAND|wx.ALL, 5)

btns = wx.StdDialogButtonSizer()
btns.AddButton(okay)
btns.AddButton(cancel)
btns.Realize()
sizer.Add(btns, 0, wx.EXPAND|wx.ALL, 5)

self.SetSizer(sizer)
sizer.Fit(self)

app = wx.PySimpleApp()
dlg = MyDialog()
dlg.ShowModal()
dlg.Destroy()
app.MainLoop()

数据传递的验证器
examples:

import wx
import pprint

about_txt = """\
The validator used in this example shows how the validator
can be used to transfer data to and from each text control
automatically when the dialog is shown and dismissed."""
class DataXferValidator(wx.PyValidator):# 声明验证器
def __init__(self, data, key):
wx.PyValidator.__init__(self)
self.data = data
self.key = key
def Clone(self):
return DataXferValidator(self.data, self.key)
def Validate(self, win):# 没有验证数据
return True
def TransferToWindow(self):# 对话框打开时被调用
textCtrl = self.GetWindow()
textCtrl.SetValue(self.data.get(self.key, ""))
return True
def TransferFromWindow(self):# 对话框关闭时被调用
textCtrl = self.GetWindow()
self.data[self.key] = textCtrl.GetValue()
return True
class MyDialog(wx.Dialog):
def __init__(self, data):
wx.Dialog.__init__(self, None, -1, "Validators: data transfer")
# Create the text controls
about = wx.StaticText(self, -1, about_txt)
name_l = wx.StaticText(self, -1, "Name:")
email_l = wx.StaticText(self, -1, "Email:")
phone_l = wx.StaticText(self, -1, "Phone:")
# 将验证器与窗口部件相关联
name_t = wx.TextCtrl(self, validator=DataXferValidator(data, "name"))
email_t = wx.TextCtrl(self, validator=DataXferValidator(data, "email"))
phone_t = wx.TextCtrl(self, validator=DataXferValidator(data, "phone"))
# Use standard button IDs
okay = wx.Button(self, wx.ID_OK)
okay.SetDefault()
cancel = wx.Button(self, wx.ID_CANCEL)
# Layout with sizers
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(about, 0, wx.ALL, 5)
sizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5)
fgs = wx.FlexGridSizer(3, 2, 5, 5)
fgs.Add(name_l, 0, wx.ALIGN_RIGHT)
fgs.Add(name_t, 0, wx.EXPAND)
fgs.Add(email_l, 0, wx.ALIGN_RIGHT)
fgs.Add(email_t, 0, wx.EXPAND)
fgs.Add(phone_l, 0, wx.ALIGN_RIGHT)
fgs.Add(phone_t, 0, wx.EXPAND)
fgs.AddGrowableCol(1)
sizer.Add(fgs, 0, wx.EXPAND|wx.ALL, 5)
btns = wx.StdDialogButtonSizer()
btns.AddButton(okay)
btns.AddButton(cancel)
btns.Realize()
sizer.Add(btns, 0, wx.EXPAND|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
app = wx.PySimpleApp()
data = { "name" : "Jordyn Dunn" }
dlg = MyDialog(data)
dlg.ShowModal()
dlg.Destroy()
wx.MessageBox("You entered these values:\n\n" + pprint.pformat(data))
app.MainLoop()

实时验证控制输入
examples:

import wx
import string
about_txt = """\
The validator used in this example will validate the input on the fly
instead of waiting until the okay button is pressed. The first field
will not allow digits to be typed, the second will allow anything
and the third will not allow alphabetic characters to be entered.
"""
class CharValidator(wx.PyValidator):
def __init__(self, flag):
wx.PyValidator.__init__(self)
self.flag = flag
self.Bind(wx.EVT_CHAR, self.OnChar)# 绑定字符事件
def Clone(self):
return CharValidator(self.flag)
def Validate(self, win):
return True
def TransferToWindow(self):
return True
def TransferFromWindow(self):
return True
def OnChar(self, evt):# 数据处理
key = chr(evt.GetKeyCode())
if self.flag == "no-alpha" and key in string.letters:
return
if self.flag == "no-digit" and key in string.digits:
return
evt.Skip()
class MyDialog(wx.Dialog):
def __init__(self):
wx.Dialog.__init__(self, None, -1, "Validators: behavior modification")
# Create the text controls
about = wx.StaticText(self, -1, about_txt)
name_l = wx.StaticText(self, -1, "Name:")
email_l = wx.StaticText(self, -1, "Email:")
phone_l = wx.StaticText(self, -1, "Phone:")
# 绑定验证器
name_t = wx.TextCtrl(self, validator=CharValidator("no-digit"))
email_t = wx.TextCtrl(self, validator=CharValidator("any"))
phone_t = wx.TextCtrl(self, validator=CharValidator("no-alpha"))
# Use standard button IDs
okay = wx.Button(self, wx.ID_OK)
okay.SetDefault()
cancel = wx.Button(self, wx.ID_CANCEL)
# Layout with sizers
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(about, 0, wx.ALL, 5)
sizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5)
fgs = wx.FlexGridSizer(3, 2, 5, 5)
fgs.Add(name_l, 0, wx.ALIGN_RIGHT)
fgs.Add(name_t, 0, wx.EXPAND)
fgs.Add(email_l, 0, wx.ALIGN_RIGHT)
fgs.Add(email_t, 0, wx.EXPAND)
fgs.Add(phone_l, 0, wx.ALIGN_RIGHT)
fgs.Add(phone_t, 0, wx.EXPAND)
fgs.AddGrowableCol(1)
sizer.Add(fgs, 0, wx.EXPAND|wx.ALL, 5)
btns = wx.StdDialogButtonSizer()
btns.AddButton(okay)
btns.AddButton(cancel)
btns.Realize()
sizer.Add(btns, 0, wx.EXPAND|wx.ALL, 5)
self.SetSizer(sizer)
sizer.Fit(self)
app = wx.PySimpleApp()
dlg = MyDialog()
dlg.ShowModal()
dlg.Destroy()
app.MainLoop()

你可能感兴趣的:(Scripts)