Rishi N
Rishi N

Reputation: 67

Label Tkinter Issue

So I have been wanting to make a timer using tkinter that will go on for a particular period of time. The code seems to be working fine and I am getting the output too, but for some reason, if I am resizing or moving the window, the timer pauses by itself and resumes automatically when the resizing is done. If the window is destroyed before the timer ends, I am getting error that reads

Traceback (most recent call last):
  File "countdownclock.py", line 23, in <module>
    timer()
  File "countdownclock.py", line 16, in timer
    label.config(text = '{:02d}:{:02d}'.format(mins,secs))
  File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 1646, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Program Files\Python39\lib\tkinter\__init__.py", line 1636, in _configure
    self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".!label"

Below is the code I am using. The program is meant to run for 2 minutes

from tkinter import * 
from tkinter.ttk import *
import time

root = Tk()
root.title("Clocky")

label = Label(root, font=("screaming-neon",45),background = "black", foreground = "cyan")
label.pack(anchor="center")

def timer():
    mins = 0
    secs = 0
    while mins<2:
        #clocktime = '{:02d}:{:02d}'.format(mins,secs)
        label.config(text = '{:02d}:{:02d}'.format(mins,secs))
        time.sleep(1)
        secs = secs+1
        if secs==60:
            secs=0
            mins=mins+1
        root.update()
timer()
mainloop()

Thank you for your help

Upvotes: 0

Views: 139

Answers (1)

Derek
Derek

Reputation: 2244

Your problem was connected to the use of time.sleep so I've removed it and used after to drive your clock.

I've also added a chime (just for fun)

import tkinter as tk
# from tkinter import ttk

root = tk.Tk()
root.title("Clocky")
root.geometry("250x73")

def closer(event=None):
    root.destroy()

label = tk.Label(root, font = "screaming-neon 45",
                 bg = "black", fg = "cyan", text = "00:00")

label.pack(fill = tk.BOTH, anchor = tk.CENTER)

mins = 0
secs = -1 # IS NECESSARY 

def timer():
    global mins, secs
    #clocktime = "{:02d}:{:02d}".format(mins, secs)
    secs = secs + 1
    if secs == 60:
        secs = 0
        mins = mins + 1
    label.config(text = "{:02d}:{:02d}".format(mins, secs))
    if mins < 2:
        root.after(1000, timer)
    else:
        root.bell(0)
        root.after( 1000, closer)

root.bind("<Escape>", closer)
root.after(1000, timer)
root.mainloop()

Upvotes: 1

Related Questions