那麼第一個問題是,每次遍歷for循環時,都會覆蓋self.button和self.label實例。你永遠不會創建一個名爲「self.label1」的變量。有幾種方法可以解決這個問題。這裏有一個簡單的方法來做到這一點:
import wx
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent=parent)
self.panel=wx.Panel(self)
for i in range(5):
self.button=wx.Button(self.panel, -1, label='b'+str(i), pos=(20,30*i))
self.button.Bind(wx.EVT_BUTTON, self.on_button)
self.label=wx.StaticText(self.panel, -1, label='label'+str(i), pos=(120,30*i), name='label'+str(i))
def on_button(self, event):
b=event.GetEventObject().GetLabel()
if b.endswith('1'):
newLabel = "sss"
self.resetLabel('1', newLabel)
elif b.endswith('2'):
self.resetLabel('2', "Number 2!")
#----------------------------------------------------------------------
def resetLabel(self, number, newLabel):
""""""
lbls = [widget for widget in self.panel.GetChildren() if isinstance(widget, wx.StaticText)]
for lbl in lbls:
if number in lbl.GetLabel():
lbl.SetLabel(newLabel)
break
x=wx.App()
y=MyFrame(None).Show()
x.MainLoop()
你也可以使用SETATTR和getattr的創建self.label(1-N)動態如下:
import wx
class MyFrame(wx.Frame):
def __init__(self, parent):
wx.Frame.__init__(self, parent=parent)
self.panel=wx.Panel(self)
for i in range(5):
setattr(self, "button%s" % i,
wx.Button(self.panel, -1, label='b'+str(i), pos=(20,30*i))
)
btn = getattr(self, "button%s" % i)
btn.Bind(wx.EVT_BUTTON, self.on_button)
setattr(self, "label%s" % i,
wx.StaticText(self.panel, -1, label='label'+str(i), pos=(120,30*i), name='label'+str(i))
)
print
def on_button(self, event):
b=event.GetEventObject().GetLabel()
if b.endswith('1'):
self.label1.SetLabel("sss")
elif b.endswith('2'):
self.label2.SetLabel("Number 2!")
x=wx.App()
y=MyFrame(None).Show()
x.MainLoop()
非常感謝Mike – sne 2013-03-25 14:16:50