4

I'm trying to do a chess clock using tkinter, and to do so i'm using the root.after method from the class Tk of tkinter. When the program starts, it runs really well, but after a while the clock start to get slower and slower, but if i start shaking my mouse, the clock starts to run fast again. For a clock, time precision is crucial, so i can't afford to run the program in the way that is working now. How can i solve this problem?

def RunClock(self):
        """
        Method that runs and change the clock info
        """
        #t0 = time.time()

        if self.playing:
            #Time remaining in milliseconds
            clock = self.clock


            minutes = clock//60000
            clock %= 60000

            sec = clock//1000
            clock %= 1000

            mil = clock//10

            #If the turn is of player 1
            if self.turn == 1:
                self.WriteClock(self.canvas1, self.play1, "%.2i:%.2i:%.2i"%(minutes, sec, mil))
            else:
                self.WriteClock(self.canvas2, self.play2, "%.2i:%.2i:%.2i"%(minutes, sec, mil))

            #tf = time.time()

            #deltat = (tf - t0)

            #s = 1 - deltat

            self.rel -= 1

            #if s > 0:
            #    time.sleep(s/1000)
            #else:
            #    self.rel += s*1000

            self.root.after(1, self.RunClock)

Note: The time to run the function is very low (you can calculate it with the commented tf and t0 variables), so i didn't even consider it in the time interval

  • There's not enough code here to figure out what's going wrong. On the other hand, don't do this: `clock = self.clock`. It's a habit you do not want to start. – dursk Nov 23 '14 at 05:03
  • Which operating system are you on? – User Nov 23 '14 at 09:01
  • 2
    For one thing, there's no reason to run the clock code every millisecond. Do chess players really time themselves to the thousandths of a second? There's really no need to use less than a second or half-second. – Bryan Oakley Nov 23 '14 at 14:02
  • to avoid the drift, you could [lock the clock with a timer](http://stackoverflow.com/a/26609843/4279). – jfs Jan 15 '15 at 13:51

1 Answers1

1

As Brian pointed out reducing the time interval will likely be the easiest solve to your question. Alternately though, you could try running your timer separately on it's own thread and having it run asynchronously and send it threading events as is discussed here:

Python threading.timer - repeat function every 'n' seconds

Community
  • 1
  • 1
Murphy4
  • 1,499
  • 2
  • 15
  • 22