I'm trying to make a mode for a simple game where you catch items as they fall down using tkinter.
In this mode, you have 60 seconds to catch as many items as you can. All the timer methods I've tried pause the whole program
...tried using an empty label, but the .after pauses the whole program
timerlabel = tkinter.Label(text="")
def timer():
global t, timerdisplay
while t > 0:
t -= 1
timerlabel.after(1000)
c.delete(timerdisplay)
timerdisplay = c.create_text(200, 12, text=t)
c.update()
any idea how to do this?
CodePudding user response:
This is the better way to do it, specifically because after(n) freezes the program for the given time period. Create a function that accepts a number and displays that number. Then, it subtracts one and then reschedules itself to run one second in the future until the number becomes zero.
def timer(t):
global timerdisplay
c.delete(timerdisplay)
timerdisplay = c.create_text(200, 12, text=t)
if t >= 1:
c.after(1000, timer, t-1)
timer(timerdisplay, 10)
To optimize this, you can pass in the canvas item along with the number. You can also just reconfigure the text item rather than deleting and restoring it.
def timer(timerdisplay, t):
c.itemconfigure(timerdisplay, text=t)
if t >= 1:
c.after(1000, timer, timerdisplay, t-1)
timerdisplay = c.create_text(200, 12)
timer(timerdisplay, 10)
