标签类型问题



所以我一直想用tkinter制作一个计时器,它将持续一段特定的时间。代码似乎工作得很好,我也得到了输出,但由于某种原因,如果我正在调整大小或移动窗口,计时器会自行暂停,并在调整大小完成后自动恢复。如果在计时器结束之前窗口被销毁,我得到的错误读取

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 FilesPython39libtkinter__init__.py", line 1646, in configure
return self._configure('configure', cnf, kw)
File "C:Program FilesPython39libtkinter__init__.py", line 1636, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".!label"

下面是我使用的代码。程序应该运行2分钟

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

谢谢你的帮助

您的问题与使用time.sleep有关,因此我已将其删除并使用after来驱动您的时钟。

我还添加了一个编钟(只是为了好玩)

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

相关内容

最新更新