我正在制作一个 mp3 播放器,我需要一个前进按钮,但似乎无法弄清楚

问题描述

所以,为了播放这首歌,我的代码是:

def play_song(*args):
    idx = song_list.curselection()[0]
    song = song_dict[idx][1]  
    pygame.mixer.music.load(song)
    pygame.mixer.music.play(loops=0)

虽然现在我需要一个前进按钮,所以我最初的计划是:

def next_song():
     next_one = song_list.curselection()
     next_one = next_one[0]+1
     song = song_list.get(next_one)

那会给我下一首歌的名字,但我不知道如何使用 Pygame 播放它。

解决方法

看起来你想让我看看这里,我觉得这很简单。获取当前选区并在当前选区添加一个并清除当前选区,然后将当前选区设置为新选区,然后加载并播放歌曲。所以函数会是这样的:

def next_song():
    try:
        idx = song_list.curselection()[0] + 1 # The initial curselection + 1
        song_list.selection_clear(0,'end') # Clear the old selection
        song_list.selection_set(idx) # Set selection to new item
        song_list.activate(idx) # Set the entire focus to new item?
        
        song = song_dict[idx][1] # Get the corresponding song from the dictionary 
        pygame.mixer.music.load(song) # Load the song
        pygame.mixer.music.play(loops=0) # Play the song
    except IndexError: # If no item selected 
        pass # Ignore the error

示例: 因此,如果当前选择为 1,那么它会删除 1 并将其设为 2,并将当前选择设置为 2 并激活它(默认为下划线),每次按下按钮时都会像这样进行。