Tkinter - widget with 'grid_remove' built in as part of class
<p>I am doing some experimentation with tkinter and have run into a bit of trouble with grid_remove. I can use it fine with a simple button that links to a command that removes a specific widget, but I can't seem to get it to work when it is part of a class.</p>

<p>When I try and run this:</p>

<pre><code>class Text(object):

def __init__(self, label_text, r, c):
    self.label_text = label_text
    self.r = r
    self.c = c
    self.label = Label(root, text = self.label_text).grid(row = self.r, column = self.c)

def hide(self):
    self.grid_remove()
def show(self):
    self.grid()
</code></pre>

<p>I get the error:</p>

<pre><code>AttributeError: 'Text' object has no attribute 'grid_remove'
</code></pre>

<p>I also want to have a button controlling the visibility of the widgets, so how should I specify a command for the button? At the moment I have:</p>

<pre><code>button = Button(root, text = 'Hide', command = one.hide()).grid(row = 2)
</code></pre>

<p>So, for others who have come across this problem, here's what I needed to change in order to get my script to work.</p>

<p>First of all, writing <code>.grid()</code> right after creating the <code>Label</code> was assigning the value of <code>grid</code> to <code>self.label</code> instead of assigning <code>Label</code> to it. The value of <code>grid</code> is a value of none so that was creating the first error. After fixing that part of the code it looks like:</p>

<pre><code>self.label = Label(root, text = self.label_text)
self.label.grid(row = self.r, column = self.c)
</code></pre>

<p>The next problem was defining the <code>hide</code> and <code>show</code> functions. I was trying to <code>grid_remove</code> the whole <code>Text</code> class. However, the <code>Text</code> class comprises of many different things, one of which is a <code>Label</code>. I needed to specify to apply <code>grid_remove</code> to only the <code>Label</code> instead of the whole class. After fixing the definitions they look like this:</p>

<pre><code>def hide(self):
    self.label.grid_remove()

def show(self):
    self.label.grid()
</code></pre>

<p>And the last error was the command in the buttons. I had written <code>command = one.hide()</code>. However, for some reason that is not known to me, I instead had to write only <code>command = one.hide</code> without the parentheses. After fixing that the buttons look like:</p>

<pre><code>button = Button(root, text = 'Hide', command = one.hide).grid(row = 2)
</code></pre>

<p>So the reason my script wasn't working was not due to one simple error but a combination of all of these. I hope this will help someone else in the future!</p>

python python-3.x tkinter