有没有办法让 tkinter 在打开时立即执行命令?

Is there a way to make tkinter execute a command instantly upon opening?

我目前只是在测试一些简单的想法,以锻炼计划的想法为例。我是 python 的新手,所以这更像是一个测试。我想要发生的是打开一个带有锻炼的 window(只是一个 tkinter 标签),然后在后台被动地有一个语音识别命令 运行 捕捉说 "next" 的人。我不想让人们告诉我如何使其他位更有效,因为我知道这很糟糕。

我只是想要一个解决方案,在显示 "5 pressups" 标签时被动地执行命令 SpeechRecognition1 运行。有办法吗?

from tkinter import *
import sys
import speech_recognition as sr

def NextWorkout1():
    workout1.destroy()
    Workout2()

def Workout1():
    global workout1

    workout1 = Tk()

    workout1.geometry("300x44")
    workout1.configure(background="lightblue")
    workout1.resizable(0,0)
    workout1.title("Pressups")

    insLabel = Label(workout1, text="5 pressups", fg="red", bg="lightblue", font="Arial 25 bold")
    insLabel.pack()

    workout1.mainloop()


def Workout2():
    global workout2

    workout2 = Tk()
    workout2.geometry("300x50")
    workout2.configure(background="lightblue")
    workout2.resizable(0,0)
    workout2.title("Starjumps")

    insLabel = Label(workout2, text="15 starjumps", fg="red", bg="lightblue", font="Arial 25 bold")
    insLabel.pack()

    workout2.mainloop()

def SpeechRecognition1():
    r = sr.Recognizer()

    with sr.Microphone() as source:
        audio = r.listen(source)

    for i in range(1):
        command = (r.recognize_google(audio))

        if command == "next":
            NextWorkout1()
        else:
            print("hi")

def SpeechRecognition2():
    global WorkoutNumber

    WorkoutNumber = 0
    r = sr.Recognizer()

    with sr.Microphone() as source:
        audio = r.listen(source)

    for i in range(1):
        command = (r.recognize_google(audio))

        if command == "next":
            NextWorkout2()

        else:
            print("hi")

Workout1()

将 after_idle 函数与您的函数一起用作回调函数

顺序

from threading import Thread

workout1 = Tk()

thread = Thread(target = SpeechRecognition1)
workout1.after_idle(thread.start)

workout1.mainloop()