从按钮向面板添加新的statictext

时间:2014-02-16 20:57:23

标签: python wxpython

大家好我有一个非常简单的GUI,我有一个面板和一个静态文本已经在面板中显示,现在我有一个按钮在同一个面板和第二个文本,我现在想要的是,当我点击按钮显示第一个下面的第二个文本。这是我的代码,我知道它必须是简单的但我找不到它我需要你的帮助

先谢谢。

    import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(320, 350))

        lyrics1 = '''I'm giving up the ghost of love
in the shadows cast on devotion
She is the one that I adore
creed of my silent suffocation
Break this bittersweet spell on me
lost in the arms of destiny'''

        lyrics2 = '''There is something in the way
You're always somewhere else
Feelings have deserted me
To a point of no return
I don't believe in God
But I pray for you'''

        panel = wx.Panel(self, -1)
        wx.Button(panel, -1, "Button1", (0,0))
        wx.StaticText(panel, -1, lyrics1, (45, 25), style=wx.ALIGN_CENTRE)
        wx.StaticText(panel, -1, lyrics2, (45, 190), style=wx.ALIGN_CENTRE)
        self.Centre()

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, 'statictext.py')
        frame.Show(True)
        self.SetTopWindow(frame)
        return True

app = MyApp(0)
app.MainLoop()

1 个答案:

答案 0 :(得分:1)

您需要存储您可能想要更改的所有内容的引用..

self.button =  wx.Button(panel, -1, "Button1", (0,0))
...
self.lyrics2 = lyrics2

接下来你不想添加该文本(歌词2)

    self.txt1 = wx.StaticText(panel, -1, lyrics1, (45, 25), style=wx.ALIGN_CENTRE)
    self.txt2 = wx.StaticText(panel, -1, "", (45, 190), style=wx.ALIGN_CENTRE)

这仍然会创建您可能想要在按钮侦听器中执行的文本字段(但不会放入歌词),但我们会将其保存以供日后使用...

接下来你需要创建一个事件处理程序来处理按下时的按钮

 def OnButtonPress(self,event):
     #do something in this case we will set our text
     self.txt2.SetLabel(self.lyrics2)

然后你需要将按钮绑定到它的事件处理程序

 self.button.Bind(wx.EVT_BUTTON,self.OnButtonPress) # do this right after creating button

然后它应该工作...仍然有问题,但这是一个简单的事件处理程序