Search code examples
pythonpython-2.7wxpython

wxPython, error when trying to get value from textctrl


I am trying to learn Python and wxPython; I am making a simple window that should print the contents of a textctrl element on the console. However, I get this error:

AttributeError: 'Frame' object has no attribute 't_username'

Here is the interested portion of the code:

import sys, wx
app = wx.App(False)

class Frame(wx.Frame):

    def Login(self, e):
        tmp = self.t_username.GetValue()
        print tmp

    def __init__(self, title):
        wx.Frame.__init__(self, None, title=title, size=(400, 250))
        panel = wx.Panel(self)

        m_login = wx.Button(panel, wx.ID_OK, "Login", size=(100, 35), pos=(150,165))


        t_username = wx.TextCtrl(panel, -1, pos=(100, 50), size=(150, 30))
        m_login.Bind(wx.EVT_BUTTON, self.Login)

frame = Frame("Login Screen")
frame.Show()
app.MainLoop()

I tried to change the name of the Frame class, the Bind line to

    self.Bind(wx.EVT_BUTTON, self.Login, m_login)

and removing self. from tmp, but it didn't work. Thanks for your help.


Solution

  • You just need to make t_username an attribute of the Frame class by adding self. in front of it.

    import wx
    app = wx.App(False)
    
    
    class Frame(wx.Frame):
    
        def Login(self, e):
            tmp = self.t_username.GetValue()
            print tmp
    
        def __init__(self, title):
            wx.Frame.__init__(self, None, title=title, size=(400, 250))
            panel = wx.Panel(self)
    
            m_login = wx.Button(
                panel, wx.ID_OK, "Login", size=(100, 35), pos=(150, 165))
    
            self.t_username = wx.TextCtrl(panel, -1, pos=(100, 50), size=(150, 30))
            m_login.Bind(wx.EVT_BUTTON, self.Login)
    
    frame = Frame("Login Screen")
    frame.Show()
    app.MainLoop()