while循环后不继续执行代码

Not proceeding with code after while loop

我正在尝试使用 Tkinter 制作一个简单的数字时钟。但是,在我使用“while True”更新变量和标签后,它不会创建 window,即使那部分没有缩进。这是我的代码:

from datetime import datetime
from tkinter import *

root = Tk()
root.geometry('400x200')

while True
    now = datetime.now()

    current_time = now.strftime("%H:%M:%S")

    clock = Label(root, text = current_time)
    clock.pack()


root.update()
``

我之前没有写过任何 python,但是我想 while true 总是正确的,因此你有一个无限循环,你的变量 now 不断更新新的时代,无法摆脱循环

点击此处了解如何使用 tkinter 创建时钟。 https://www.geeksforgeeks.org/python-create-a-digital-clock-using-tkinter/

您的代码将永远不会退出循环,因为 while 将始终以非常高的速度循环,因为条件始终为 (True)。

while True:
...

程序卡在这部分会继续执行。

为了解决问题,将 while True 逻辑移入 thread(使用 threading 模块中的 Thread)。

这是我们使用 clock.after(400, update) 的另一种简单方法,它将在 400 毫秒后调用并更新我们使用的标签 mainloop 以确保 main 不会退出,直到我们的 window没有关闭。

from datetime import datetime
from tkinter import *

root = Tk()
root.geometry('400x200')

clock = Label(root)
clock.pack()

def update():
    now = datetime.now()
    current_time = now.strftime("%H:%M:%S")
    print(current_time)
    clock.config(text=current_time)
    clock.after(400, update)



root.update()

update()

mainloop()