Search code examples
pythonwxpython

How to call a variable from one function to another?


In wxPython I'm trying to define a variable from one function (in the instantiator) to call into another (not in the instantiator, but still in the class)

I've seen people fix other peoples problems in their situations, and I've tried other peoples, but it just doesn't work for me.

class NamePrompts(wx.Frame):
    def __init__(self, *args, **kw):
        super(NamePrompts, self).__init__(*args, **kw)

        panl = wx.Panel(self)

        textboxtest = wx.TextCtrl(panl) # defining textboxtest as a text box
        textboxtest.Bind(wx.EVT_TEXT, self.OnKeyTyped)

        read = wx.Button(panl, label="Print", pos=(0, 25))
        read.Bind(wx.EVT_BUTTON, self.PrintText)

    def PrintText(self, event):
        typedtext = event.textboxtest.GetString() # attempting to call the same textbox here
        wx.StaticText(wx.Panel(self), label=typedtext, pos=(25, 25))

if __name__ == '__main__':
    app = wx.App()
    frm = NamePrompts(None, title='Basketball Game')
    frm.SetSize(0,0,1920,1040)
    frm.Show()
    app.MainLoop()

I get this error:

AttributeError: 'CommandEvent' object has no attribute 'textboxtest'
Traceback (most recent call last):
  File "textboxtest.py", line 19, in PrintText
    typedtest = event.textboxtest.GetString() # attempting to call the same text box here

Solution

  • Welcome to StackOverflow.

    The easiest way to achieve what you want is to use self when creating the wx.TextCtrl so it is available from methods other than __init__ and then directly accessing the value of the wx.TextCtrl from other methods.

    import wx
    
    class NamePrompts(wx.Frame):
        def __init__(self, *args, **kw):
            super(NamePrompts, self).__init__(*args, **kw)
    
            panl = wx.Panel(self)
    
            self.textboxtest = wx.TextCtrl(panl) # defining textboxtest as a text box
            #self.textboxtest.Bind(wx.EVT_TEXT, self.OnKeyTyped)
    
            read = wx.Button(panl, label="Print", pos=(0, 25))
            read.Bind(wx.EVT_BUTTON, self.PrintText)
    
        def PrintText(self, event):
            typedtext = self.textboxtest.GetValue() # attempting to call the same textbox here
            print(typedtext)
            wx.StaticText(wx.Panel(self), label=typedtext, pos=(25, 25))
    
    if __name__ == '__main__':
        app = wx.App()
        frm = NamePrompts(None, title='Basketball Game')
        frm.SetSize(50,50,300,300)
        frm.Show()
        app.MainLoop()
    

    Nevertheless, if you want to learn how to pass custom variables with an event you can check the use of lambda functions and the partial module.