0

I was trying to make a stopwatch in python but every time it stops working beacause of overflow, can someone please fix this??

Code:

import time
from tkinter import *
cur=time.time()
root = Tk()
def functio():
 while True:
 s = time.time()-cur
 l1 = Label(root,text=s)
 l1.pack()
 l1.destroy()
 time.sleep(0.5)
Button(root,text='Start',command=functio).pack()
root.mainloop()
asked Nov 21, 2021 at 20:55

3 Answers 3

1

The while loop will block tkinter mainloop from handling pending events, use after() instead.

Also it is better to create the label once outside the function and update it inside the function:

import time
# avoid using wildcard import
import tkinter as tk
cur = time.time()
root = tk.Tk()
def functio():
 # update label text
 l1['text'] = round(time.time()-cur, 4)
 # use after() instead of while loop and time.sleep()
 l1.after(500, functio)
tk.Button(root, text='Start', command=functio).pack()
# create the label first
l1 = tk.Label(root)
l1.pack()
root.mainloop()

Note that wildcard import is not recommended.

answered Nov 22, 2021 at 4:00
Sign up to request clarification or add additional context in comments.

Comments

1

Flow of execution can never exit your endless while-loop. It will endlessly block the UI, since flow of execution can never return to tkinter's main loop.

You'll want to change your "functio" function to:

def functio():
 s = time.time()-cur
 l1 = Label(root,text=s)
 l1.pack()
 l1.destroy()
 root.after(500, functio)

That being said, I'm not sure this function makes much sense: You create a widget, and then immediately destroy it?

answered Nov 21, 2021 at 21:52

Comments

1

You'll want to do something like this instead:

import time
from tkinter import *
root = Tk()
def functio():
 global timerStarted
 global cur
 # check if we started the timer already and
 # start it if we didn't
 if not timerStarted:
 cur = time.time()
 timerStarted = True
 s = round(time.time()-cur, 1)
 # config text of the label
 l1.config(text=s)
 # use after() instead of sleep() like Paul already noted
 root.after(500, functio)
timerStarted = False
Button(root, text='Start', command=functio).pack()
l1 = Label(root, text='0')
l1.pack()
root.mainloop()
answered Nov 21, 2021 at 23:26

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.