views:

374

answers:

3

I need to code a program with GUI in python (I'm thinking of using TKinter, 'cause it's easy, but I'm open to suggestions).

My major problem is that I don't know how to code a timer (like a clock... like 00:00:00,00 hh:mm:ss,00 ) I need it to update it self (that's what I don't know how to do)

A: 

How about wxPython?

There is built-in classes called wx.Timer and wx.TaskBarIcon for that

S.Mark
+1  A: 

The key is using the after() method of widgets.

See http://www.pythonware.com/library/tkinter/introduction/x9507-alarm-handlers-and-other.htm

codeape
+3  A: 

Tkinter root windows have a method called "after" which can be used to schedule a function to be called after a given period of time. If that function itself calls after, you've setup up an automatically recurring event.

Here is a working example:

import Tkinter
import time

class App():
    def __init__(self):
        self.root = Tkinter.Tk()
        self.label = Tkinter.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

    def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

Bear in mind that after doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.

Bryan Oakley
@Bryan Oakley: Thank you for the example GUI code. For users of Python 3.1.2, you need to replace "Tkinter" by "tkinter". Everything else in the code stays the same.
Winston C. Yang
Clarification: Replace __all__ occurrences of "Tkinter" by "tkinter".
Winston C. Yang
@Winston C. Yang. Really? Why? That code runs perfectly fine on my box. Though, to be honest I only tested it with python 2.5, 2.6 and 1.7. If I do as you suggest, the code doesn't work on any of those versions.
Bryan Oakley
+1, Good, clear example.
Jords