我正在尝试制作一个程序,它有一个计时器和一个显示您以前的时间的标签。我使用相同的变量(结果)来显示计时器的文本和时间列表的文本,但有时两者之间存在 0.01 或 0.02 的差异。
我尝试将结果变量保存到另一个变量,然后将timer_label文本与list_label同时更改为新变量,但这甚至无法更新timer_label上的文本 根本不。 timer_label.update() 和 root.update_idletasks() 也没有解决问题。
def timer_start():
global begin_time, timer_allow
timer_allow = True
# Allows refresh loop to occur
begin_time = time.time()
# Stores time of timer start
refresher()
# Calls refresh loop
def refresher():
global begin_time, timer_allow, result
cur = time.time()
# Stores the current time
result = round(cur - begin_time, 2)
# Calculates and displays time since timer start
timer_label.config(text=result)
# Updates timer text
if timer_allow:
root.after(10, refresher)
# Loops the refresher function every hundredth of a second
def timer_end():
global timer_allow, result, num1, num2, num3, time_list
timer_allow = False
# Stops the refresher loop
num3 = num2
num2 = num1
num1 = result
time_list = (str(num1) + " " + str(num2) + " " + str(num3))
# Creates the string for the times list
list_label.config(text=time_list)
# Updates the times list
定时器停止后,定时器和时间列表应该显示相同的时间,但有时时间会相差0.01或0.02。
最佳答案
嘿,我运行了你的代码,出现的第一个问题是这个
NameError: name 'num2' is not defined
在timer_end()内部,我相信而不是:
num3 = num2
num2 = num1
num1 = result
你可能想要这个:
num1 = result
num2 = num1
num3 = num2
第一次调用timer_end()时,num2尚未初始化。此外,即使您事先初始化了所有 3 个,在 tkinter 窗口中也只有 num1 会发生变化。
至于你的主要问题,我认为0.01的差异正在出现,因为在你将timer_allow设置为False之后(在timer_end()内部),refresher()最后一次被调用(refresher()只会发现运行该行后,timer_allow 为 false:
timer_label.config(text=result)
)。这意味着在 timer_allow 设置为 False 之后,结果会在 tkinter 窗口中再次更新一次。要纠正这个问题,您可以尝试以下操作:
def refresher():
global begin_time, timer_allow, result
cur = time.time()
# Stores the current time
result = round(cur - begin_time, 2)
# Calculates and displays time since timer start
if timer_allow:
timer_label.config(text=result)
# Updates timer text
root.after(10, refresher)
# Loops the refresher function every hundredth of a second
这似乎对我有用,据我所知,0.01 的差异已经消失了。
哦,就像上面提到的 Klaus D. 一样,避免全局变量并使用参数、对象等通常是更好的使用方法。
关于python - 在单独的标签文本中使用时,变量具有不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57121777/