[Tutor] using a Timer

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Oct 24 03:30:49 CEST 2004



On Sat, 23 Oct 2004 seanf at email.arizona.edu wrote:

> Quoting Kent Johnson <kent_johnson at skillsoft.com>:
>
>
> > Looking at the rest of your code, you are overusing self (abusing your
> > self? ;). Normally you only use self for variables that need to be shared
> > between two methods or that need to persist between method calls. Temporary
> > variables don't have to be stored in the instance.
>
> ahh, thank you. It seemed excessive. I just had a general misconception about
> scope in Python, but I seem to have it straight now. Also, the text box is
> working great now.
>
> Here's the new problem. I want to create a button that will change the model
> every 1 second or so, and then another button to stop it. I thought maybe a
> timer would work, but it only seems to run once.

Hi Sean,


Ah, it sounds like you want to use the after() method in Tkinter.  Don't
use Timer(): it's meant for use with threads.  There's an alternative way
to do the kind of interactive update you're doing, and this involves
after().


after() tells Tkinter to call some function "after" some timed delay.
For example, here is a small clock that updates itself every second:

###
"""Small clock application.  Shows how to use after() to keep a repeated
event going."""

from Tkinter import *
import time


class MyFrame(Frame):
    def __init__(self, root):
        Frame.__init__(self, root)
        self.label = Label(self)
        self.label.pack()

    def update_and_repeat(self):
        """Updates the text in the label, and reschedules another update
        after a second."""
        self.label.configure(text="The time is: " + time.ctime())
        self.after(1, self.update_and_repeat)


if __name__ == '__main__':
    root = Tk()
    frame = MyFrame(root)
    frame.pack()
    frame.update_and_repeat()
    mainloop()
###



Note that it keeps itself alive by rescheduling another
update_and_repeat(), over an over.  That rescheduling can be easily
controlled by some condition.  In pseudocode:

    if we_should_keep_going:
        self.after(1, self.update_and_repeat)


An alternative approach uses threads, but I don't like talking about them.
*grin* They often make things much more complicated than the situation
warrants, and for your problem, threads are overkill.


Hope this helps!



More information about the Tutor mailing list