简体   繁体   中英

How can I play audio with playsound and type in an entry box at the same time in tkinter?

I want to type something in the user_text entry box while the play_audio function is running

I tried the following code:

from tkinter import *
from playsound import playsound

root = Tk()


def play_audio():
    playsound('audio.mp3')


play_audio_button = Button(root, text='Play audio', command=play_audio)
user_text = Entry(root)

play_audio_button.pack()
user_text.pack(padx=10, pady=10)

mainloop()

but it doesn't let me do anything while the audio is playing in the background. It only lets me type after the audio is finished.

I also tried doing the same thing withouth tkinter and it works:

def play_audio():
    playsound('audio.mp3')


play_audio()
play_audio_input = input('Your text: \n')

It does let me type while the audio is playing in the background that way.

So how can I get it to work in tkinter?

playsound can run sound in the background, you should use threads if you need to loop the sound or something more than just running a single sound file.

def play_audio():
    playsound('audio.mp3', block=False)

if you want to loop the sound you don't need multiprocessing, the threading module is perfectly usable for running tasks in the background, which will run the audio in another thread, leaving the main thread to run your GUI.

import threading

def play_audio():
    while True:
        playsound('audio.mp3')

play_audio_button = Button(root, text='Play audio', command=lambda: threading.Thread(play_audio).start())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM