简体   繁体   中英

Tkinter - widget with 'grid_remove' built in as part of class

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.

When I try and run this:

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

I get the error:

AttributeError: 'Text' object has no attribute 'grid_remove'

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:

button = Button(root, text = 'Hide', command = one.hide()).grid(row = 2)

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

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

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

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

def hide(self):
    self.label.grid_remove()

def show(self):
    self.label.grid()

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

button = Button(root, text = 'Hide', command = one.hide).grid(row = 2)

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM