[Tkinter-discuss] A Button command callback question...

johnmc johnmc at velseis.com
Mon Jul 18 13:09:20 CEST 2011

On Sun, 17 Jul 2011 20:34:58 -0700 (PDT), GKalman wrote
> The following code fragment works OK.  Question: why?
> #======================================
> from Tkinter import *
> root=Tk()
> lbl=Label(root,text='1').pack()
> def doIt():
>     lbl.config(bg="yellow")
> btn=Button(root,text="do", bg="cyan",command=doIt).pack()
> root.mainloop()
> #=======================================

The code fragment you posted does not work OK, assuming that if by OK you intend the 
label background to change yellow upon invocation of the "do" button.

The reason why it does not work is you have bound lbl to the return of the pack 
method, which is None.  Obviously, you cannot configure the background colour of a 
None object.

What I'm sure you intended was:

from Tkinter import *
root = Tk()
lbl = Label(root, text='1')

def doIt():

btn = Button(root, text='do', bg='cyan', command = doIt)


Now, upon pressing the "do" button, the label background changes to yellow.

> My question is: how is the instance lbl.config(...) recognized in the doIt
> callback fn when called from the main w/o an argument referencing lbl?

The reason why has to do with scope.  You have defined lbl in the global scope.  Thus 
the name "lbl" is available (defined) to the local scope of the function doIt.  This 
may have been purely accidentally fortuitous on your part but it is expected behaviour.



This message has been scanned for viruses and
dangerous content by MailScanner, and is
believed to be clean.

More information about the Tkinter-discuss mailing list