I'm trying to create a game in Tkinter, and I want to have a While loop run only x times a second. Evenly spaced.
I have tried dividing 1 by X and using the time module to wait that amount. But it didn't run it 60 times a second, only 50.
def start(self):
Frame.__init__(self, self.master)
self.fpLength = 1 / self.fps
while True:
# Code here
time.sleep(self.fpLength)
I expect the code to run 60 times a second. But it runs around 55.
If you are doing it in thread (see my comment) you can try something like
def start(self):
Frame.__init__(self, self.master)
# self.fpLength = 1 / self.fps
while True:
# Code here
clock = time.perf_counter() * 60 # measer time in 1/60 seconds
sleep = int(clock) + 1 - clock # time till the next 1/60
time.sleep(sleep/60)
Of cause you can use self.fps instead of constant 60 here, I use it just for more clear comments.