Need help with Tkinter

Ivan Van Laningham ivanlan at callware.com
Tue Dec 14 00:08:00 EST 1999


Hi All--

rodzilla2000 at my-deja.com wrote:
> 
> I'm trying to learn python/Tkinter...
> 
> I tried modifying the hello.py script that guido included in the 1.5.2
> source.
> 
> Here's what I was trying to do (to learn while tinkering...)
> 
> Change the "Hello World" button a "Add Exit Button" that would put
> another button on the screen to allow exiting the program.
> 
> Add the additional exit button...
> 
> Here's the code:
>
#!/usr/local/bin/python

# Button test...

import sys
from Tkinter import *

#main routine
def main():
    global root  # Added
    root=Tk()
    btnAddButton=Button(root)
    btnAddButton['text']='Add Exit Button'
    btnAddButton['command']=subAddButton   # You must mention
subAddButton, not call it
    btnAddButton.pack()

    #start mainloop
    root.mainloop()  #<===  You must call mainloop, not just mention it.

def subAddButton(event=0):
    global root  # Added
    btnExitButton=Button(root)
    btnExitButton['text']='Exit Program'
    btnExitButton['command']=subExit   #see below
    btnExitButton.pack()

def subExit():
    sys.exit(0)


#execute the main routine
main()
===========END OF CODE

subAddButton is the function object; subAddButton() _calls_ the function
object.  If you say btnAddButton['command']=subAddButton(root) you are
calling the function.  Since the function has been called, naturally it
makes the button appear before you tell it to.

Since you can't control what parameters are passed to command functions,
you have to make the root window a global (otherwise, only main() can
see it) so that it can be seen inside the subAddButton() function.

Finally, you need to call root.mainloop(); when you do so, it doesn't
end until you push the exit button.  If you only mention the name, the
main() function just returns, and exits the program.  I don't know how
it ran on your system; pure bad luck, I guess.

You'd do better to organize your program as a class; then you don't have
to pepper your callbacks with global this, global that.

<take-two-classes-and-call-me-in-the-morning>-ly y'rs,
Ivan;-) 
----------------------------------------------
Ivan Van Laningham
Callware Technologies, Inc.
ivanlan at callware.com
ivanlan at home.com
http://www.pauahtun.org
See also: 
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
----------------------------------------------




More information about the Python-list mailing list