我需要帮助在 Pygame 中创建一个循环

I need help by creating a loop in Pygame

我有以下代码

def play_music():
    song = playlist.get(ACTIVE)
    next_one = playlist.curselection()
    next_one = next_one[0]+1
    pygame.mixer.music.load(song)
    pygame.mixer.music.play(loops=0)
    pygame.mixer.music.set_endevent()
    for event in pygame.event.get():
        playlist.selection_clear(0,END)
        playlist.activate(next_one)
        playlist.select_set(next_one,last=None)
        song = playlist.get(ACTIVE)
        pygame.mixer.music.queue(song)

当我 运行 代码时,它会播放一首歌曲,然后播放播放列表中的下一首歌曲。但我想将其实现为一个循环。它应该对下一首歌曲进行排队,播放列表中的歌曲数量与播放列表中的歌曲一样多(即:我在播放列表中有 5 首歌曲,然后我想要,我只需要按一次播放按钮,然后播放所有 5 首歌曲,一个一个。)

我的程序图片: https://i.stack.imgur.com/T5Gch.png 我希望你能帮助我。提前感谢您的帮助。

这是我对 Utilising the pygame.mixer.music.get_endevent()

的回答中的示例

它创建自己的事件 MUSIC_END 并将其分配给音乐 endevent

稍后加载一首歌曲并将下一首歌曲添加到队列中。

当第一首歌结束时,它将 generate/send 事件 MUSIC_END。但这需要 运行 一直 for event in pygame.event.get() 来捕获此事件和 运行 将下一首歌曲添加到队列的代码。

当它完成下一首歌曲时,它将再次 generate/send 事件 MUSIC_END 循环将捕捉并再次将歌曲添加到队列中。

随着歌曲的增多,它需要将所有歌曲保留在列表中,并记住必须将列表中的哪首歌添加到队列中。

编辑:

适用于歌曲列表并更改标签上文本的版本。

import pygame
import tkinter as tk

def check_event():
    global current_song
    global next_song
    
    for event in pygame.event.get():
        if event.type == MUSIC_END:
            print('music end event')

            # calculate index for current song (which was takes from queue) 
            #current_song = (current_song + 1) % len(songs)
            current_song = next_song
            
            # add title for current song
            label['text'] = songs[current_song]
            
            # calculate index for next song            
            next_song = (current_song + 1) % len(songs)
            
            # add to queue next song
            pygame.mixer.music.queue(songs[next_song])

    # run again after 100ms (0.1s)
    root.after(100, check_event)

def play():
    label['text'] = songs[current_song]
    pygame.mixer.music.play()

# --- main ---

songs = [
    'audio1.wav',
    'hello-world-of-python.mp3',
]

current_song = 0
next_song = 1

pygame.init()    

# define new type of event
MUSIC_END = pygame.USEREVENT+1

# assign event to `endevent`
pygame.mixer.music.set_endevent(MUSIC_END)

# play first song
pygame.mixer.music.load(songs[current_song])

# calculate index for next song            
next_song = (current_song + 1) % len(songs)

# add to queue next song
pygame.mixer.music.queue(songs[next_song])

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()