TLSK
TLSK

Reputation: 273

Add a new statictext to a panel from button

Hello guys I have a very simple GUI: I have a panel and a static text already shown in the panel, now I have a button in the same panel and a second text.

What I want now is that, when I click the button to show the second text under the first.

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()

Upvotes: 0

Views: 415

Answers (1)

Joran Beasley
Joran Beasley

Reputation: 114098

you need to store a reference to everything you may want to change ..

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

next you dont want to add that text to begin with (lyrics 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)

this still creates the textfield (but doesnt put in the lyrics) which you likely want to do in your button listener but we will save that for later...

next you need to create an event handler to deal with the button when its pressed

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

then you need to bind the button to its event handler

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

then it should work ... still has issues but thats a simple event handler

Upvotes: 1

Related Questions