A smallish Tkinter question

Fredrik Lundh fredrik at pythonware.com
Thu Apr 21 11:35:02 EDT 2005


Mediocre Person wrote:

> What I want: A little window to open with a 0 in it. Every second, the
> 0 should increment by 1.
> What I get: A one second delay, see the window with a 1 in it, and then
> nothing appears to happen. Never see the 0, never see a 2.  Any quick
> clues? Thanks. Nick. (Python 2.4, Win98).

simple solution:

    def run(self): #also tried self,parent
        sleep(1.0)
        self.time = self.time + 1
        self.display["text"] = str(self.time)
        self.update() # make sure to process all outstanding events

smarter solution:

    def run(self):
        self.display["text"] = str(self.time)
        self.time = self.time + 1
        self.after(1000, self.run)
        # no need to use update in this case

even smarter solution:

    import time

    TICK = 1.0 # time between updates, in seconds

    def run(self):
        self.display["text"] = str(self.time)
        self.time = self.time + 1
        delay = TICK - (time.time() % TICK)
        self.after(int(delay*1000), self.run)
        # no need to use update in this case

also see:

    http://tkinter.unpythonic.net/wiki/TkinterDiscuss

</F>




More information about the Python-list mailing list