[Tutor] Layering Canvas widgets with Tkinter
jfouhy@paradise.net.nz
jfouhy at paradise.net.nz
Mon Jun 20 07:55:25 CEST 2005
Quoting Phillip Hart <phillip.hart at gmail.com>:
> So far, I've tried using a single Tk window, creating a series of canvas
> widgets, each containing a series of buttons. When pressed, each button
> calls a function which uses .grid_remove() on the current canvas and
> creates a new canvas with new buttons in its place (a new menu).
Your logic is a bit confused, I think.
What you are aiming for, I think, is something like this:
Display Main Menu
"menu 1" pushed --> hide main menu, display menu1
"back" pushed --> hide menu1, display main menu
"menu 2" pushed --> hide main menu, display menu2
"back" pushed --> hide menu2, display main menu
"menu 3" pushed --> hide main menu, display menu3.
One way you could do this is to create all four menus, and then use callbacks
that simply show/hide as appropriate.
For example:
######## Note that I have replaced leading spaces with underscores #####
######## You will need to undo this to run the program #################
from Tkinter import *
def switch(hide, show):
____hide.grid_forget()
____show.grid(sticky=N+S+E+W)
tk = Tk()
# This is necessary, otherwise the canvas shrinks to the size of the button(s)
it contains.
# You could also use width= and height= to give the canvases a specific size.
tk.grid_rowconfigure(0, weight=1)
tk.grid_columnconfigure(0, weight=1)
main = Canvas(tk)
menu1 = Canvas(tk, background='green')
menu2 = Canvas(tk, background='pink')
menu3 = Canvas(tk, background='yellow')
for i, m in enumerate((menu1, menu2, menu3)):
____Button(main, text='Menu %d' % i, command=lambda m=m: switch(main, m)).grid()
____Button(m, text='Back', command=lambda m=m: switch(m, main)).grid()
main.grid()
tk.mainloop()
##################################
I am only creating the canvases once, and then just using grid() and
grid_forget() to hide/show them as appropriate. In your code, you created a new
canvas with every call to menu1/menu2/menu3. Also, you never called grid_forget
on any of those canvases (so they never disappeared).
Finally, I made all the canvases children of tk, rather than making
menu1/menu2/menu3 children of main. If menu1 were a child of main, then to
display menu1, you would have to hide the buttons (because menu1 would display
inside main).
----
Additional comments:
- grid_forget is, I think, exactly the same as grid_remove.
- Are you sure you want to be using canvases at all? Geometry managers like
grid are normally used with Frames. If you want to display widgets on a canvas,
the normal way to do it is to use canvas.create_window.
--
John.
More information about the Tutor
mailing list