运行 一个 python 计时器在调用其他方法后

Running a python timer after a other method has been called

你好,我现在正在为学校做一个项目,我正在使用 Kivy 框架。它基于 python 编码,我正在寻找我的问题的答案。

t = 5

def countdown(t):
    
    while t:
        mins, secs = divmod(t, 60)
        timer = '{:02d}:{:02d}'.format(mins, secs)
        print(timer, end="\r")
        time.sleep(1)
        t -= 1
      
    print('Fire in the hole!!')

class ResetPopup(Popup):
    pass

class Widgets(Widget):
    def btn(self):
        popup = ResetPopup()
        popup.open()
        countdown(int(t))

class MyApp(App)
    def build(self):
        return Widgets()

现在,当我使用按钮打开弹出窗口时,计时器首先开始 运行,然后弹出窗口将打开。我正在寻找一种先打开弹出窗口然后启动计时器的方法。

有什么建议吗?

尝试使用 on_open 方法。当弹出窗口为 opened.You 时会触发此方法,只需将该方法添加到您的 class 定义中即可:

class ResetPopup(Popup):
    def on_open(self):
        countdown(int(t)) #This fires your function when popup is opened

更多信息: https://kivy.org/doc/stable/api-kivy.uix.popup.html