Need help with Tkinter

Matt Gushee mgushee at havenrock.com
Mon Dec 13 21:55:54 EST 1999


rodzilla2000 at my-deja.com writes:

> Change the "Hello World" button a "Add Exit Button" that would put
> another button on the screen to allow exiting the program.
> 
> =========START OF CODE
> # Button test...
> 
> import sys
> from Tkinter import *
> 
> #main routine
> def main():
>     root=Tk()
>     btnAddButton=Button(root)
>     btnAddButton['text']='Add Exit Button'
>     btnAddButton.pack()
> 
>     #start mainloop
>     root.mainloop
> 
> def subAddButton(parent):
>     btnExitButton=Button(parent)
>     btnExitButton['text']='Exit Program'
>     btnExitButton['command']=subExit   #see below
> 
> def subExit():
>     sys.exit(0)
> 
> 
> #execute the main routine
> main()
> ==========END OF CODE
> 
> When I run this code, the exit button is already displayed.  The "Add

Right, because in:

>     btnAddButton['command']=subAddButton(root)   # See below

... evaluating this statement *calls the function subAddButton()*. So
the button is created when main() is executed, and since subAddButton
returns ... returns what? Maybe None -- I can't remember offhand, but
anyway it's nothing useful to you.

It's been a while since I did any Tkinter programming, but as far as I
can recall you can't pass an argument to a button command, because you
can't use any parentheses when you assign the command to the
button. You could either make root a global variable -- ugly, but it
works in a pinch -- or you could create an event binding like:

	btnAddButton.bind('<Button-1>', subAddButton)

then subAddButton has an 'event' argument:

	def subAddButton(event=None):

'event' being an object that is automatically passed when the event 
binding is invoked -- it's __dict__ attribute contains all sorts of
useful information, such as the widget that captured the event:

		caller = event.__dict__['widget']

This is, of course, the preferred object-oriented-type solution
... though it's less simple than we might wish, eh?

Hope this helps a bit.

-- 
Matt Gushee
Portland, Maine, USA
mgushee at havenrock.com
http://www.havenrock.com/



More information about the Python-list mailing list