TkInter:两个按钮之间的传输变量

TkInter: transport variable between two buttons

有人能告诉我是否可以在 tkinter 中的两个按钮之间传输变量!?例如:我想测量按下两个按钮之间的时间并将其打印到标签上...

from tkinter import *
import time

start_time = 0.0

...
def press_start():
    start_time = time.time()

def press_end():
    estimated_time = time.time() - start_time
    lbl_time.config(text=f"Estimated time: {estimated_time }")

...
btn_start = Button(text="Start", command=press_start)
btn_end = Button(text="Start", command=press_end)
lbl_time = Label()
...

press_start函数只修改函数范围内的start_timestart_time 外部 函数仍然引用 0.0.

def press_start():
    start_time = time.time() 
    print(start_time) # would still output time.time()
print(start_time) # outputs 0.0

像这样使用 global 关键字:

def press_start():
    global start_time
    start_time = time.time()
print(start_time) # outputs time.time() now

我建议阅读的相关主题是 references and variable scopes