我正在制作音乐播放器(我已经完成了大部分工作),并且我刚刚制作了它,以便在歌曲播放完后自动播放下一首歌曲(def checkFinished()
就是这样做的。 )
我遇到的问题是在checkFinished()
内使用一个循环(以查看歌曲是否结束),并且该循环似乎破坏了Tkinter列表框-我认为这是删除循环的循环解决此问题。
这是我的代码:
import os
from tkinter.filedialog import askdirectory
import pygame
from mutagen.id3 import ID3
from tkinter import *
root = Tk()
root.minsize(300,300)
listofsongs = []
realnames = []
v = StringVar()
songlabel = Label(root,textvariable=v,width=35)
index = 0
def updatelabel():
global index
global songname
v.set(realnames[index])
def nextSong(event):
global index
index += 1
pygame.mixer.music.load(listofsongs[index])
pygame.mixer.music.play()
updatelabel()
def prevSong(event):
global index
index -= 1
pygame.mixer.music.load(listofsongs[index])
pygame.mixer.music.play()
updatelabel()
def stopSong(event):
pygame.mixer.music.stop()
v.set("")
def playSong(event):
pygame.mixer.music.play()
print("Now playing {}".format(listofsongs[index]))
def checkFinished(finished):
while True:
for event in pygame.event.get():
if event.type == finished:
print("Finished {}\n\n".format(listofsongs[index]))
nextSong(event)
def directorychooser():
directory = askdirectory()
os.chdir(directory)
for files in os.listdir(directory):
if files.endswith(".mp3"):
realdir = os.path.realpath(files)
try:
audio = ID3(realdir)
realnames.append(audio['TIT2'].text[0])
except:
realnames.append(files)
listofsongs.append(files)
pygame.init()
pygame.mixer.init()
clock = pygame.time.Clock()
finished = pygame.USEREVENT + 1
pygame.mixer.music.set_endevent(finished)
pygame.mixer.music.load(listofsongs[0])
pygame.mixer.music.play()
print("\n\nNow playing {}".format(listofsongs[0]))
checkFinished(finished)
directorychooser()
label = Label(root,text='Music Player',width="20",height="5")
label.pack()
listbox = Listbox(root,width="80")
listbox.pack()
realnames.reverse()
for items in realnames:
listbox.insert(0,items)
realnames.reverse()
playButton = Button(root,text="Play Song",width="15")
playButton.pack()
stopButton = Button(root,text="Stop Song",width="15")
stopButton.pack()
nextButton = Button(root,text="Next Song",width="15")
nextButton.pack()
previousButton = Button(root,text="Previous Song",width="15")
previousButton.pack()
playButton.bind("<Button-1>",playSong)
stopButton.bind("<Button-1>",stopSong)
nextButton.bind("<Button-1>",nextSong)
previousButton.bind("<Button-1>",prevSong)
songlabel.pack()
root.mainloop()
谢谢!
答案 0 :(得分:0)
由于while
中的checkFinished(...)
循环将阻塞主线程,请尝试删除while
循环并改用root.after()
:
def checkFinished(finished):
for event in pygame.event.get():
if event.type == finished:
print("Finished {}\n\n".format(listofsongs[index]))
nextSong(event)
root.after(10, checkFinished, finished)