[英]Label not updating in tkinter
我相信 2 天前我問了一個非常相似的問題,但由於 mod 告訴我查看其他類似問題但沒有一個解決方案有效,所以它被關閉了。 有誰知道如何修復錯誤。 這是代碼,目前它所做的只是打印並顯示序列中的第一個數字:
import tkinter as tk
#import time
window = tk.Tk()
window.title("Hello wold")
window.geometry("300x300")
timer = int(input("time in seconds "))
def update():
global timer
timer -= 1
print(timer)
hello = tk.Label(window, textvariable = timer)
hello.pack()
for i in range(timer):
window.after(1000, update)
tk.mainloop()
將 textvariable= timer 更改為 text= timer
您的代碼中有幾個問題:
input()
tk.mainloop()
阻塞,直到根 window 關閉。 然而,下一次迭代將引發異常,因為根 window 被破壞。 實際上 for 循環不是必需的。下面是一個修改過的例子:
import tkinter as tk
window = tk.Tk()
window.title("Hello World")
window.geometry("300x300")
# it is not recommended to use console input() in a GUI app
#timer = int(input("time in seconds: "))
timer = 10 # use sample input value
def update(timer=timer):
hello['text'] = timer
if timer > 0:
# schedule to run update() again one second later
hello.after(1000, update, timer-1)
# create label once and update its text inside update()
hello = tk.Label(window)
hello.pack()
update() # start the after loop
# should run mainloop() only once
window.mainloop()
import tkinter as tk
#import time
window = tk.Tk()
window.title("Hello wold")
window.geometry("300x300")
timer = int(input("time in seconds "))
hello = tk.Label(window, text= timer)
hello.pack()
def update():
global timer
timer -= 1
print(timer)
hello.config(text=timer)
for i in range(timer):
window.after(1000, update)
tk.mainloop()
像這樣的東西應該工作
嘗試這個:
import tkinter as tk
import time
window = tk.Tk()
window.title("Countdown Timer")
window.geometry("300x300")
timer = int(input("time in seconds "))
#var = tk.StringVar()
def update(cnt):
if cnt > 0:
window.after(1000, update, cnt-1)
print(cnt)
hello['text'] = cnt
hello = tk.Label(window, text=cnt)
#hello['text'] = timer
hello.pack()
update(timer)
tk.mainloop()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.