[Tutor] Showing/hiding widgets in Tkinter

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


The Green Tea Leaf wrote:

> > 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
> 
> Unfortunately, it doesn't work. I can see the label flashing when I
> press the button but it's not visible unless I press the button again.

I don't understand that sentence. If you press the button the label should 
disappear. When you press it again it should become visible again.

I added some noise to your initial script and saved the placement state:

import sys
import Tkinter as tk

def toggle():
    if mylabel.visible:
        btnToggle["text"] = "Show Example"
        print "Now you don't"
        mylabel.place_forget()
    else:
        mylabel.place(mylabel.pi)
        print "Now you see it"
        btnToggle["text"] = "Hide Example"
    mylabel.visible = not mylabel.visible

root = tk.Tk()

print "TkVersion", tk.TkVersion
print "TclVersion", tk.TclVersion
print "Python version", sys.version_info

mylabel = tk.Label(text="Example")
mylabel.visible = True
mylabel.place(x=20, y=50)
mylabel.pi = mylabel.place_info()

btnToggle = tk.Button(text="Hide Example", command=toggle)
btnToggle.place(x=70, y=150)

root.mainloop()

That does what it's expected to do over here.



More information about the Tutor mailing list