那么第一个问题是,在通过 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()