简体   繁体   中英

Why does the sound play before the rest of the code?

I want to have the block turn green and the sound play together, or if that's not possible then I would like to have the block turn green first. but I can't find out why the sound is playing first... Here is my code:

def number(*args):
try:
    x = r.get()
    if x <= '3':
        s.configure('Danger.TFrame', background='green',
                    borderwidth=5, relief='raised')
        ttk.Frame(root, width=200, height=200, style='Danger.TFrame')
        winsound.PlaySound('dotto.wav', winsound.SND_FILENAME)
        print("green")
    elif x >= "5":
        s.configure('Danger.TFrame', background='red',
                    borderwidth=5, relief='raised')
        ttk.Frame(root, width=200, height=200, style='Danger.TFrame')
        print("red")
    else:
        s.configure('Danger.TFrame', background='orange',
                    borderwidth=5, relief='raised')
        ttk.Frame(root, width=200, height=200, style='Danger.TFrame')
        print("orange")
except:
    print("error")

I am using winsound, and the file thats playing is dotto.wav.

Thanks,

winsound.PlaySound() is a blocking method call by default, which means it will wait until playing the sound is finished before continuing with anything else. In your case "anything else" probably includes rendering the (now green) block.

So in your example code, your Block is changed to green before starting to play the sound, but you probably can't see that, because it isn't re-drawn on the screen, until after the sound has finished.

To tell winsound you don't want to wait for the sound to end, you need to pass the winsound.SND_ASYNC parameter.

winsound.PlaySound('dotto.wav', winsound.SND_FILENAME | winsound.SND_ASYNC)

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