退出时 tkinter 中的标签错误 window

Label error in tkinter while exiting window

我正在尝试通过 python tkinter 制作数字时钟。我的代码是

import tkinter,time

def exiter():
    root.destroy()

root=tkinter.Tk()
root.title("Digital Clock")
root.geometry("340x100")
root.resizable(False,False)
root.protocol("WM_DELETE_WINDOW",exiter)

def time_setter():
    hr=tkinter.Label(root,font=('k',60,'bold'),text=time.strftime("%H:%M:%S"))
    hr.grid(row=0,column=0)

    

while True:
    root.update()
    time_setter()

关闭 window 后出现错误

Traceback (most recent call last):
  File "c:\Users\Tanmay Daga\OneDrive\Documents\Programming\Clock-Tkinter\digital_clock.py", line 20, in <module>
    time_setter()
  File "c:\Users\Tanmay Daga\OneDrive\Documents\Programming\Clock-Tkinter\digital_clock.py", line 13, in time_setter
    hr=tkinter.Label(root,font=('k',60,'bold'),text=time.strftime("%H:%M:%S"))
  File "C:\Program Files\Python39-32\lib\tkinter\__init__.py", line 3145, in __init__
    Widget.__init__(self, master, 'label', cnf, kw)
  File "C:\Program Files\Python39-32\lib\tkinter\__init__.py", line 2569, in __init__
    self.tk.call(
_tkinter.TclError: can't invoke "label" command: application has been destroyed

如何在 window 关闭时打破循环。
我怎么知道 window 何时关闭

from tkinter import *
from time import strftime

def clock_tick():
    string = strftime('%H:%M:%S %p')
    lbl.config(text=string)#set the text
    lbl.after(1000, time)#updater 
    
root=Tk() 
lbl = Label(root, font=('calibri', 40, 'bold'),
            background='purple',
            foreground='white')
lbl.pack(anchor = 'center')
clock_tick() 
root.title("Digital Clock")
root.geometry("340x100")
root.resizable(False,False)
root.mainloop() #this is the loop you are looking for instead of the while loop

循环错误。对于 tkinter,有一个更好用的内置循环。如果您使用 root.mainloop() 设置循环,则使用 X 退出将提供一个干净的退出。这是您尝试做的一个很好的例子 https://www.geeksforgeeks.org/python-create-a-digital-clock-using-tkinter/