如何在不命名的情况下更改statictext的标签

时间:2013-09-20 09:02:49

标签: python wxpython

以下是我的代码,它创建没有名称的静态文本 有没有办法在这段代码中更改标签?

import wx


class Mainframe(wx.Frame):
    def __init__(self, parent):
        wx.Frame.__init__(self, parent)
        self.panel = wx.Panel(self)
        wx.StaticText(self.panel, id=1, label='test', pos=(10, 30))
        wx.StaticText(self.panel, id=2, label='test', pos=(10, 60))


if __name__ == '__main__':
        app = wx.App(False)
        frame = Mainframe(None)
        frame.Show()
        app.MainLoop()

1 个答案:

答案 0 :(得分:0)

首先,不要指定自己的ID,特别是1000以下,因为这些可能在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()