[Tutor] Buttons automatically executing

Michael Lange klappnase at freenet.de
Wed Jun 15 23:43:26 CEST 2005


On Wed, 15 Jun 2005 14:31:55 -0500
Phillip Hart <phillip.hart at gmail.com> wrote:


Hi Phillip,

> #!usr/bin/python
> 
> from Tkinter import *
> 
> def location(x,y):
> print "I am in row ",x," and column ",y
> 
> 
> root=Tk()
> root.geometry('300x300')
> can=Canvas(root,width=250, height=250)
> 
> bimage=PhotoImage(file='sq1.gif')
> 
> b1=Button(can,bg="black",image=bimage,command=location(0,0)).grid(row=0,column=0)

That's an error which frequently happens to Tkinter beginners.
When you assign the button's command like this the command is executed immediately
after button creation, the correct usage is:

    b1 = Button(can, command=location)

without the parentheses; however if you need to pass arguments to the callback,
you can use a lambda expression like this:

    b1 = Button(can, command = lambda x=0, y=0 : location(x, y))

Another problem in this line that doesn't matter here, but might cause confusion later on
is the use of grid() ; note that grid() returns None, so actually you set your variable
b1 to None which is probably not what you intended; if you need to keep a reference to
the Button object you need to split the above into two statements:

    b1 = Button(can, <opts>)
    b1.grid()

If you don't need a reference you can simply do:

    Button(can,<opts>).grid(row=0,column=0)

without creating a (quite useless) variable.

I hope this helps

Michael



More information about the Tutor mailing list