Home > Software design >  Tkinter crash in python
Tkinter crash in python

Time:11-22

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()

CodePudding user response:

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?

CodePudding user response:

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()

CodePudding user response:

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.

  • Related