Python 等待变量更改而不停止程序的其余部分

问题描述 投票:0回答:1

我正在 tkinter 中编写带有 UI 的录音机,当我按下按钮时,它会触发标题为该按钮名称的录音,以及一些数据。当我按下停止按钮时,我希望程序停止录制该文件并保存它。问题是,它唯一停止的地方是程序开始录制的打开文件内。这是我的代码片段:

def button_click(button_text):
 print(f"You clicked the button labeled {button_text}")
 with rec.open(f"{button_text}_judge{judge}.wav", "wb") as recfile2:
     recfile2.start_recording()
     #wait here until stop_button_click function is called and finished
     print("Finished!")
     
def stop_button_click():
 print("Stop button clicked!")
 #Do something here to trigger the button_click function to continue

为了提供一些上下文,按钮与这些功能交互的方式如下:

# Create a frame to hold the stop button separately
stop_frame = tk.Frame(root)
stop_frame.pack(side=tk.LEFT, fill=tk.Y)  # Pack it on the left side

# Create the stop button
stop_button = tk.Button(stop_frame, text="Stop", command=stop_button_click)
stop_button.pack(pady=5)  # Add padding

# Create a frame to hold the buttons inside the canvas
button_frame = tk.Frame(canvas)
canvas.create_window((0, 0), window=button_frame, anchor="nw")

# List of button labels
button_labels = ["Button 1", "Button 2", "Button 3", "Button 4", "Button 5", "Button 6", "Button 7"]  # Add more buttons here

# Create and arrange buttons within the frame
for i, label in enumerate(button_labels):
 button = tk.Button(button_frame, text=label, command=lambda label=label: button_click(label))
 button.pack(pady=5)  # Add padding between buttons

我想过以某种方式使用 asyncio,但我不确定如何让它正常工作,因为停止按钮是由 tkinter 触发的,当我让它工作时,UI 在开始录制时冻结(使用while True 循环)。

python tkinter audio python-asyncio
1个回答
0
投票

您可以使用 Tkinter 变量和

wait_variable
来完成此操作。

recording_stopped = tk.BooleanVar(root, False)

def button_click(button_text):
   print(f"You clicked the button labeled {button_text}")
   with rec.open(f"{button_text}_judge{judge}.wav", "wb") as recfile2:
       recfile2.start_recording()
       root.wait_variable(recording_stopped)
       print("Finished!")

def stop_button_click():
    print("Stop button clicked!")
    recording_stopped.set(True)

这将创建一个初始化为 false 的布尔变量。当记录开始时,

wait_variable
会阻塞,直到通过单击停止按钮设置变量为止。

© www.soinside.com 2019 - 2024. All rights reserved.