问题
I want a tkinter
label to show nothing when a sound effect has finished.
I've been researching the www on how to create/initialise/catch the end of music event with no luck.
def play_btn():
if mixer.music.get_busy():
mixer.music.fadeout(1000)
snd_fyl.set(snd_list.get(ACTIVE))
mixer.music.load(snd_dir+"/"+snd_list.get(ACTIVE)+"mp3")
mixer.music.play()
def stop_btn():
mixer.music.stop()
clear_label()
def clear_label():
snd_fyl.set("")
snd_lbl1 = LabelFrame(MainWindow, text="Sound effect playing", labelanchor=N)
snd_playing_lbl = Label(snd_lbl1, width=40, textvariable=snd_fyl)
Obviously play_btn function plays a sound effect from a list.
The stop_btn
function prematurely halts the sound effect and clears the label.
The clear_label
function has been created in readiness for the end_of_song
event
回答1:
You have to use set_endevent()
to set value which it will send to event queue when music has finished.
MUSIC_END = pygame.USEREVENT+1
pygame.mixer.music.set_endevent(MUSIC_END)
And then you can test it in event loop
if event.type == MUSIC_END:
print('music end event')
It will print text when music has finished - but not when you stop it or pause it.
BTW: on Linux I see this text few milliseconds before it ends playing music.
Full working example - but without tkinter
import pygame
pygame.init()
screen = pygame.display.set_mode((400, 300))
MUSIC_END = pygame.USEREVENT+1
pygame.mixer.music.set_endevent(MUSIC_END)
pygame.mixer.music.load('sound.wav')
pygame.mixer.music.play()
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == MUSIC_END:
print('music end event')
if event.type == pygame.MOUSEBUTTONDOWN:
# play again
pygame.mixer.music.play()
pygame.quit()
EDIT: Example with tkinter
import pygame
import tkinter as tk
def check_event():
for event in pygame.event.get():
if event.type == MUSIC_END:
print('music end event')
label['text'] = ''
root.after(100, check_event)
def play():
label['text'] = 'playing'
pygame.mixer.music.play()
# --- main ---
pygame.init()
MUSIC_END = pygame.USEREVENT+1
pygame.mixer.music.set_endevent(MUSIC_END)
pygame.mixer.music.load('sound.wav')
root = tk.Tk()
label = tk.Label(root)
label.pack()
button = tk.Button(root, text='Play', command=play)
button.pack()
check_event()
root.mainloop()
pygame.quit()
来源:https://stackoverflow.com/questions/58630700/utilising-the-pygame-mixer-music-get-endevent