例子
下面的示例演示了 RadioBox 和 RadioButton 的使用。首先,在面板上放置三个按指定 wx.RB_GROUP 样式分组的 RadioButton。
self.rb1 = wx.RadioButton(pnl,11, label = 'Value A', pos = (10,10), style = wx.RB_GROUP)
self.rb2 = wx.RadioButton(pnl,22, label = 'Value B',pos = (10,40))
self.rb3 = wx.RadioButton(pnl,33, label = 'Value C',pos = (10,70))
另一方面,RadioBox 从 lblList[] 对象中读取其按钮的标签。
lblList = ['Value X', 'Value Y', 'Value Z']
self.rbox = wx.RadioBox(pnl,label = 'RadioBox', pos = (80,10), choices = lblList ,
majorDimension = 1, style = wx.RA_SPECIFY_ROWS)
声明了两个事件绑定器,一个用于无线电组,另一个用于 RadioBox。
self.Bind(wx.EVT_RADIOBUTTON, self.OnRadiogroup)
self.rbox.Bind(wx.EVT_RADIOBOX,self.onRadioBox)
相应的事件处理程序识别选定的按钮并在控制台窗口上显示消息。
def OnRadiogroup(self, e):
rb = e.GetEventObject()
print rb.GetLabel(),' is clicked from Radio Group'
def onRadioBox(self,e):
print self.rbox.GetStringSelection(),' is clicked from Radio Box'
完整的代码如下 -
import wx
class Example(wx.Frame):
def __init__(self, parent, title):
super(Example, self).__init__(parent, title = title,size = (300,200))
self.InitUI()
def InitUI(self):
pnl = wx.Panel(self)
self.rb1 = wx.RadioButton(pnl,11, label = 'Value A',
pos = (10,10), style = wx.RB_GROUP)
self.rb2 = wx.RadioButton(pnl,22, label = 'Value B',pos = (10,40))
self.rb3 = wx.RadioButton(pnl,33, label = 'Value C',pos = (10,70))
self.Bind(wx.EVT_RADIOBUTTON, self.OnRadiogroup)
lblList = ['Value X', 'Value Y', 'Value Z']
self.rbox = wx.RadioBox(pnl, label = 'RadioBox', pos = (80,10), choices = lblList,
majorDimension = 1, style = wx.RA_SPECIFY_ROWS)
self.rbox.Bind(wx.EVT_RADIOBOX,self.onRadioBox)
self.Centre()
self.Show(True)
def OnRadiogroup(self, e):
rb = e.GetEventObject()
print rb.GetLabel(),' is clicked from Radio Group'
def onRadioBox(self,e):
print self.rbox.GetStringSelection(),' is clicked from Radio Box'
ex = wx.App()
Example(None,'RadioButton and RadioBox')
ex.MainLoop()
上面的代码产生以下输出 -
从 Radio Group 中单击值 B
从 Radio Group 中单击值 C
从单选框中单击值 Y
从单选框中单击值 X