[Tutor] Layering Canvas widgets with Tkinter

Alan G alan.gauld at freenet.co.uk
Mon Jun 20 10:00:23 CEST 2005


-----------------
def menu(y):
   main.grid_remove ()
   root.update()
   if y ==1:
      menu1()
etc/...

def menu1():
   X=Canvas(root, width=200, height=200, bg="blue")
   X.grid(row=0,column=0)
   but2=Button(X,text="back",command=mainmenu)
   but2.grid()

def menu2():...
def menu3():...

root= Tk()
root.geometry('200x200')
main=Canvas(root,width=200,height=200,bg="grey")
main.grid(row=0,column=0)
root.mainloop()
--------------------

I think one problem is that you initially call your canvas main.
In menu() you then remove main, but you don't ever replace it.
Thus on subsequent calls to menu() you are not actually 
removing anything!

This is partly a result of you using global variables everywhere
and partly a result of you mixing the object creation and their 
positioning in a single function.

It would IMHO be better to make the menuN() functions simply 
return the canvas objects rather than to use grid() internally.
That way you can associate them with main... That way the code 
changes to look something like:

def menu(y):
   main.grid_remove ()
   root.update()
   if y ==1:
      main = menu1()
   main.grid(row=0,column=0)
etc/...

def menu1():
   X=Canvas(root, width=200, height=200, bg="blue")
   but2=Button(X,text="back",command=mainmenu)
   but2.grid()
   return X

The other option would e to pass main into menuN() as a 
parameter and use that instead of X but I prefer the 
approach above...

HTH

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld


More information about the Tutor mailing list