python - 标签 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()
感谢您的帮助
解决方案
您的问题与使用有关,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()
推荐阅读
- python - 子类 logging.Logger 的模式
- oracle - SQL 代理作业上的 SSIS 部署失败 - Oracle 连接管理器
- java - 如何在 mongodb 中使用嵌套文档执行可分页查询?
- python - 使用 Python 自动化 Google 表单
- cypress - 在 Cypress 中组织新的端到端测试的一般做法
- api - 是否有现有软件可以从经纪账户导入所有数据?
- javascript - 返回一个嵌套的 observable
- java - 关于oshi-core,我使用m1(macbook air)
- javascript - 从代码中的 Fancybox 中删除 Share 元素图标
- android - 设计数据库用户有很多特权