Issue
I'm programming a voice recorder with a UI in tkinter, and when I press a button, it triggers a recording titled that button's name, plus a bit of data. When I press the stop button, I want the program to stop recording that file and save it. Problem is, the only place it works to stop is inside the open file where the program starts recording. Here is a snippet of my code:
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
To give some context, the way the buttons are interacting with these functions are like this:
# 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
and
# 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
I thought of using asyncio in some way, but I'm not sure how to get it to work properly, as the stop button is triggered by tkinter and when I do get it to work, the UI freezes when it starts recording (using a while True loop).
Solution
You can do this using Tkinter variables and 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)
This creates a Boolean variable which is initialised to false. When the recording starts, wait_variable
blocks until the variable is set by clicking the stop button.
Answered By - Henry
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.