[Tutor] Showing/hiding widgets in Tkinter

Peter Otten __peter__ at web.de
Wed Apr 6 12:35:55 CEST 2011


The Green Tea Leaf wrote:

> Hi all,
> 
> I'm trying to learn a bit about how to show/hide objects using the
> available layout managers and have no problems using Pack or Grid but
> when I try to use Place then I'm missing something
> 
> My test code looks like this
> 
> from Tkinter import *
> 
> def toggle():
>     if mylabel.visible:
>         mylabel.place_forget()
>     else:
>         mylabel.place()
>     mylabel.visible = not mylabel.visible
> 
> root = Tk()
> 
> mylabel = Label(text="Example")
> mylabel.visible = True
> mylabel.place(x=20,y=50)
> 
> btnToggle = Button(text="Toggle nr two",command=toggle)
> btnToggle.place(x=70,y=150)
> 
> root.mainloop()
> 
> According to the documentation I've read I should be able to use
> 'place()' after having used 'place_forget()' to show the label at the
> same place.

Where did you read that? I only found

"""
If the configuration of a window has been retrieved with place info, that 
configuration can be restored later by first using place forget to erase any 
existing information for the window and then invoking place configure with 
the saved information.
"""

at http://www.tcl.tk/man/tcl8.5/TkCmd/place.htm

which implies that tk does not store the placement information 
automatically. Assuming that Python's Tkinter behaves the same way you can 
write

def toggle():
    if mylabel.visible:
        mylabel.pi = mylabel.place_info()
        mylabel.place_forget()
    else:
        mylabel.place(mylabel.pi)
    mylabel.visible = not mylabel.visible

> What happens is on the first click the label disappears, but when I
> click again it stays invisible (and yes, the else statement is
> executed). If I change the else-statement to
> 'mylabel.place(x=70,y=150)'
> 
> Any idea what I'm missing?





More information about the Tutor mailing list