Search code examples
pythonwxpython

Issue with .Hide() on individual widgets in wxpython


As someone pretty new to wxpython, I'm attempting to write a login script for an imaginary program. On startup, buttons ask if you want to create a new account or register a new one. When either one is clicked, I want all the widgets on the page to disappear, leaving a blank frame for other widgets to be imposed on. However I'm not sure how to .Hide() specific widgets -- my existing widgets are not being recognized as variables. Here's my relevant code:

class Welcome(wx.Frame):

    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "ImageViewer", size=(500,350))
        panel = wx.Panel(self)

        text = wx.StaticText(panel, -1, "Welcome to ImageViewer. Do you have an account?", (50,10))
        font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL)  
        text.SetFont(font)  

         yesbutton = wx.Button(panel, label="Yes,  I wish to log in", pos=(50,150), size=(150,60))
         self.Bind(wx.EVT_BUTTON, self.loginwindow, yesbutton)

        nobutton = wx.Button(panel, label="No,  I wish to register", pos=(270,150), size=(150,60))
        self.Bind(wx.EVT_BUTTON, self.registerwindow, nobutton)


    def loginwindow(self, event):
        self.Hide(self.text) #Error occurs here

AttributeError: 'Welcome' object has no attribute 'text'

I'm not sure if there is a better way of doing this (if there is please let me know) but for now I'm just not sure why I can't access these variables.


Solution

  • text isn't made an attribute of of the Welcome class, so when you try and call it in your loginwindow function it's out of scope.

    When you declare it in your init method make it self.text

    Edit: This code works.

    class Welcome(wx.Frame):
    
    def __init__(self, parent, id):
        wx.Frame.__init__(self, None, id, "ImageViewer", size=(500,350))
        panel = wx.Panel(self)
    
        self.text = wx.StaticText(panel, -1, "Welcome to ImageViewer. Do you have an account?", (50,10))
        font = wx.Font(12, wx.DEFAULT, wx.NORMAL, wx.NORMAL)  
        self.text.SetFont(font)  
    
        yesbutton = wx.Button(panel, label="Yes,  I wish to log in", pos=(50,150), size=(150,60))
        self.Bind(wx.EVT_BUTTON, self.loginwindow, yesbutton)
    
    
    def loginwindow(self, event):
        self.text.Hide() #Error occurs here