首先,不要指定您自己的 id,尤其是低于 1000 的 ID,因为它们可能会在 wxPython 内部保留。如果您想指定您的 id,请使用以下内容:
myId1 = wx.NewId()
myId2 = wx.NewId()
wx.StaticText(self.panel, id=myId1, label='test', pos=(10, 30))
wx.StaticText(self.panel, id=myId2, label='test', pos=(10, 60))
如果您想查找小部件,我建议您尝试 wxPython FindWindowBy* 方法之一,例如 wx.FindWindowById 或 wx.FindWindowByName。
这是一个简单的例子:
import wx
class Mainframe(wx.Frame):
myId1 = wx.NewId()
myId2 = wx.NewId()
def __init__(self, parent):
wx.Frame.__init__(self, parent)
self.panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
txt1 = wx.StaticText(self.panel, id=self.myId1,
label='test', name="test1")
txt2 = wx.StaticText(self.panel, id=self.myId2,
label='test', name="test2")
btn = wx.Button(self.panel, label="Find by id")
btn.Bind(wx.EVT_BUTTON, self.onFindById)
btn2 = wx.Button(self.panel, label="Find by name")
btn2.Bind(wx.EVT_BUTTON, self.onFindByName)
sizer.Add(txt1, 0, wx.ALL, 5)
sizer.Add(txt2, 0, wx.ALL, 5)
sizer.Add(btn, 0, wx.ALL, 5)
sizer.Add(btn2, 0, wx.ALL, 5)
self.panel.SetSizer(sizer)
#----------------------------------------------------------------------
def onFindById(self, event):
""""""
print "myId1 = " + str(self.myId1)
print "myId2 = " + str(self.myId2)
txt1 = wx.FindWindowById(self.myId1)
print type(txt1)
txt2 = wx.FindWindowById(self.myId2)
print type(txt2)
#----------------------------------------------------------------------
def onFindByName(self, event):
""""""
txt1 = wx.FindWindowByName("test1")
txt2 = wx.FindWindowByName("test2")
if __name__ == '__main__':
app = wx.App(False)
frame = Mainframe(None)
frame.Show()
app.MainLoop()