-2

I tried adding a timer to a game I made with Tkinter

from tkinter import *
timer = 60
def startGame(event):
    if timer == 60:
        countdown()
def countdown():
    global timer
    if timer > 0:
        timer -= 1
        timeLabel.config(text='Time left:' + str(timer))
        timer.after(1000, countdown())
window = Tk()
timeLabel = Label(window, text='time = 60 sec')
entryBox = Entry(window)
timeLabel.pack()
entryBox.pack()
window.bind('<Return>', startGame)
entryBox.pack
entryBox.focus_set()
window.mainloop()

the timer is supposed to start when you press enter in the entryBox but instead, it shows this error

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.6/tkinter/__init__.py", line 1705, in __call__
    return self.func(*args)
  File "/home/user/PycharmProjects/Game/example.py", line 5, in startGame
    countdown()
  File "/home/user/PycharmProjects/Game/example.py", line 11, in countdown
    timer.after(1000, countdown())
AttributeError: 'int' object has no attribute 'after'

I have tried converting timer to string and float by

str(timer).after(1000, countdown())     in line11
float(timer).after(1000, countdown())   in line11

if these 3 attributes(int, str, and float) don't work which will work with 'entry'.

Or how can I add a timer to my game?

Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685
akishtp
  • 3
  • 4
  • Neither integers nor floats nor strings have a method called "after". Can you explain why you expected that this method exists? – mkrieger1 Sep 19 '20 at 18:05
  • I saw this on another post on adding timers to games. And what you asked is the question I have too . how do I make it work then. or at least add a timer to my game. – akishtp Sep 19 '20 at 18:08
  • And whatever method it is you are trying to call. The second argument needs to be `countdown` rather than `countdown()`. You want the timer to call the function, not that it be called right there. – Frank Yellin Sep 19 '20 at 18:08
  • Try `window.after(1000, countdown())` – Mike67 Sep 19 '20 at 18:11
  • Yeah, that worked. thanks. Could you add that as an answer so others can find it too. thanks again. – akishtp Sep 19 '20 at 18:15
  • Not necessary, it’s already answered here: https://stackoverflow.com/questions/2400262/how-to-create-a-timer-using-tkinter – mkrieger1 Sep 19 '20 at 18:23

1 Answers1

1

To get rid of all the confusions, after() is a method of root and not timer which is int in your case. Just replace timer.after(...) with root.after(...):

if timer > 0:
    timer -= 1
    timeLabel.config(text='Time left:' + str(timer))
    timer.after(1000, countdown)

Make sure to remove the (), from countdown(), so that the command is not invoked before the 1000 ms.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46