无法在tkinter中使用配置标记文本



因此,我一直在尝试在tkinter中创建一个简单的秒表,在其中我创建了一个循环,将文本更新到新的时间,即当我单击按钮_1时,计时器标签中的下一秒。我试着用StringVar((和.config方法来做这件事,但它们都没有更新标签中的文本。代码低于

from datetime import *
from time import *
init_time = datetime(100, 1, 1, 0, 0, 0)
running = True
def clock():
while running == True:
sleep(1)
global init_time
a = init_time.strftime("%H:%M:%S")
mtime.set(a)
init_time = init_time + timedelta(seconds=1)
def stop():
global running
running = False

main = Tk()
main.geometry("500x200")
mtime = StringVar()
timer = Label(main, textvariable = mtime, width=30, bg="black", fg="white", font=(25))
timer.place(x=90, y=20)
button_1 = Button(main, text = "Start", command = clock()).place(x=170, y=120)
button = Button(main, text = "Stop", command = stop).place(x=250, y=120)
main.mainloop()

我甚至尝试将init_time转换为字符串,因为我认为文本的更新可能只适用于字符串。初始GUI窗口显示,但当我单击按钮_1时,它不起作用。

你犯了一个常见的错误,看看这两行

button_1 = Button(main, text = "Start", command = clock()).place(x=170, y=120)
button = Button(main, text = "Stop", command = stop).place(x=250, y=120)

请注意,您有clock()stop。第一个是函数调用,第二个是函数。您应该提供command的功能。使用clock替换clock()

此外,如果您对每n毫秒执行一次函数感兴趣,请查看.after,考虑以下简单计时器

import tkinter as tk
elapsed = 0
def update_timer():
global elapsed
elapsed += 1
timer['text'] = str(elapsed)
root.after(1000, update_timer)  # 1000 ms = 1 second
root = tk.Tk()
timer = tk.Label(root, text="0")
btn = tk.Button(root, text="Go", command=update_timer)
timer.pack()
btn.pack()
root.mainloop()

最新更新