-2
import tkinter as tk
import time

timer = 0

def startTimer():
    if timer == 0:
        time.sleep(1)
    elif (running):
        global timer
        timer += 1
        timeText.configure(text=str(timer))
    window.after(1000, startTimer)
    
def start():
    global running
    running = True
    
def stop():
    global running
    running = False

running = True

window = tk.Tk()


timeText = tk.Label(window, text = '0', font=("Helvetica", 80))
timeText.pack()

startButton = tk.Button(window, text = 'Start', bg='yellow', command=start)
startButton.pack(fill=tk.BOTH)

stopButton = tk.Button(window, text = 'Stop', bg='yellow', command=stop)
stopButton.pack(fill=tk.BOTH)

startTimer()
window.mainloop()

I wanted to make a stopwatch with python but I have question to you to solve this problem. when I execute this, I can find

line 10
global timer
^
SyntaxError: name 'timer' is used prior to global declaration

this error.

I tried to make this stopwatch to start without I press start button. And, I want this stopwatch to start at 0.

Can you change my code to solve the problem?

1
  • 1
    Move global timer to the line before if timer==0 in startTimer function Commented Sep 4, 2022 at 16:05

1 Answer 1

0

In order for the stopwatch to work you should fix two issues: you must declare as global both running and timer, since both are used in the startTimer function, and you should address the infinite loop that happens in the if timer == 0 part. You see, if when timer is 0 all the script does is wait, then it will never increment and thus loop indefinitely. Both issues are fixed by the code below.

def startTimer():
    global timer
    global running
    if timer == 0:
        time.sleep(1)
        timer += 1
    elif running:
        timer += 1
        timeText.configure(text=str(timer))
    window.after(1000, startTimer)

Keep in mind though that tkinter does not behave well with time, generally speaking.

Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't work... The error has gone but the timer doesn't count.
@Gryphinx I've edited my answer, take a look at it and let me know what you think.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.