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')
lbl.pack()

def doIt():
    lbl.config(bg='yellow')

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

root.mainloop()
#==========================================

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.

Regards,

John


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

_______________________________________________
Tkinter-discuss mailing list
Tkinter-discuss@python.org
http://mail.python.org/mailman/listinfo/tkinter-discuss

Reply via email to