PDA

View Full Version : my first attempt at Tk GUI in python...


inkedmn
03-11-2002, 11:39 AM
there's only one problem (that i can see). this script goes out and checks to see if i have any new mail, and if i do, it opens a small box with two buttons: Quit, or Open Mail Client (which will download the new mail). whenever i run the script, my mail client is automatically opened before the window even appears.

i'm sure this is painfully easy and i'm just overlooking it, but if somebody could give me a hand...


import poplib, os
from Tkinter import *


def drawAlert():
root = Tk()
cmd = r'start C:\\progra~1\\thebat~1\\thebat.exe'
widget = Label(root)
widget.config(text='You have new mail')
widget.pack(side=TOP, expand=YES)
widget = Button(None, text='Quit', command=sys.exit)
widget.pack()
widget1 = Button(None, text='Open Mail Client', command=os.system(cmd))
widget1.pack()
root.title('Mail Alert')
root.mainloop()

pop = poplib.POP3('pop.gmx.net')
pop.user('inkedmn@gmx.net')
pop.pass_('<password>')
msg_count = len(pop.list()[1])

if msg_count > 0:
drawAlert()
else:
sys.exit()


oh, and btw, i'm using windows right now in case anybody couldn't tell :)

t.i.a.

kmj
03-11-2002, 12:29 PM
knew the asnwer to that one before you asked it. :)
When you supply a callback function for a widget (for example, the 'command' parameter for a Button, you need to pass the function object itself. Now, when you write foo(), that is not a reference to the function. You are calling the function (by using ()). Instead you'd need foo (without the parens). Just like you use sys.exit above. To restate: sys.exit is RIGHT. sys.exit() is WRONG. Now, but what about parameters, you ask. Well, there are a few ways this can be handled:

(oh, btw, I won't lecture you on using os.system. suffice it to say that some people would consider that grounds for incarceration.)

first, use lambda. lambda is a python keyword which allows you to create anonymous functions.

lambda x,y: x+y

would return x+y

plus = lambda x,y: x+y

would make plus a function which returns x+y

so, now what you'd want to do is something like this:

widget1 = Button(None, text='Open Mail Client', command= lambda: os.system(cmd))

this simply creates an anonymous function which takes no parameters and calls os.system(cmd).

python tutorial, lambda forms. (http://python.org/doc/current/tut/node6.html#SECTION006740000000000000000)

Oh, and you're going to want to learn about object oriented programming (http://www.ibiblio.org/obp/thinkCSpy/chap12.htm) if you're playing with GUI's. Makes things much easier to understand.