首页 > 解决方案 > 标签 Tkinter 问题

问题描述

所以我一直想用 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 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"

下面是我正在使用的代码。该程序旨在运行 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()

感谢您的帮助

标签: pythontkinter

解决方案


您的问题与使用有关,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()

推荐阅读