Python tKinter-在进行新的计数之前,有没有办法摆脱现有的标签



我找到了一个倒计时代码,并对其进行了修改,使其计数到给定的数字。这一切都有效,但每次我按下按钮运行函数时,现有的标签都会保留在那里,而新的标签会放在上面。(如果我把它们打包,它们就会被放在一起(。这是因为它们是在函数内部创建的,但我似乎找不到绕过它的方法

这可能是一个新手问题,但我只是想学习:(

代码:

import time
from tkinter import *
import threading
betongtrykk = Tk()
betongtrykk.geometry("400x300")
canvas = Canvas(
betongtrykk,
bg = "#FFFFFF",
height = 300,
width = 400,
bd = 0,
highlightthickness = 0,
relief = "ridge"
)
canvas.place(x = 0, y = 0)
utnyttelseres = 65
def cd(timer_label_obj,ts):
while ts < utnyttelseres:
timer_label_obj.config(text=ts)
ts+=1
timer_label_obj.place(x=100, y=150)
time.sleep(0.01)
if ts == utnyttelseres:
timer_label_obj.config(text=utnyttelseres)
def countup(t):
timer = Label(betongtrykk)
th = threading.Thread(target=cd,args=[timer,t])
th.start()
submitCountdown = Button(betongtrykk, padx=5, pady=5, text="Submit", font=("Arial", 20), command= lambda:countup(0))
submitCountdown.place(x= 100, y=100)
betongtrykk.mainloop()

一旦倒计时完成,就可以在Label小部件上使用<widget>.destroy()方法。此方法将删除小部件并将其从屏幕上删除。

更正的代码:

import time
from tkinter import *
import threading
betongtrykk = Tk()
betongtrykk.geometry("400x300")
canvas = Canvas(
betongtrykk,
bg = "#FFFFFF",
height = 300,
width = 400,
bd = 0,
highlightthickness = 0,
relief = "ridge"
)
canvas.place(x = 0, y = 0)
utnyttelseres = 65
def cd(timer_label_obj,ts):
while ts < utnyttelseres:
timer_label_obj.config(text=ts)
ts+=1
timer_label_obj.place(x=100, y=150)
time.sleep(0.01)
if ts == utnyttelseres:
timer_label_obj.config(text=utnyttelseres)
timer_label_obj.destroy()
def countup(t):
timer = Label(betongtrykk)
th = threading.Thread(target=cd,args=[timer,t])
th.start()
submitCountdown = Button(betongtrykk, padx=5, pady=5, text="Submit", font=("Arial", 20), command = lambda:countup(0))
submitCountdown.place(x= 100, y=100)
betongtrykk.mainloop()

备用解决方案:

如果您希望在下一个倒计时开始前删除倒计时标签,可以将timer设为全局变量,并在countup中创建新的倒计时标签之前对其使用.destroy()方法。

def cd(timer_label_obj,ts):
while ts < utnyttelseres:
timer_label_obj.config(text=ts)
ts+=1
timer_label_obj.place(x=100, y=150)
time.sleep(0.01)
if ts == utnyttelseres:
timer_label_obj.config(text=utnyttelseres)
def countup(t):
global timer
try:
timer.destroy()
except NameError:
pass

timer = Label(betongtrykk)
th = threading.Thread(target=cd,args=[timer,t])
th.start()

相关内容

  • 没有找到相关文章

最新更新