【发布时间】:2020-06-25 23:57:13
【问题描述】:
我正在制作一个使用 Tkinter 作为界面的音乐播放器,并且我试图在单击时将“播放”按钮更改为“暂停”。当我点击“暂停”按钮时,它又回到了“播放”。 以下是我的代码:
from tkinter import *
import time, sys
from pygame import mixer
track_names = ['lady maria', 'cleric beast']
current_track = ''
def press(word):
global track_name
global current_track
if word == 'PLAY':
update_button_text()
for name in track_names:
window_2.delete(0, 'end')
current_track = name
window_2.configure(state='normal')
window_2.insert('end', name)
mixer.init()
mixer.music.set_volume(100)
mixer.music.load(f'C:/Users/user/Desktop/python/projects/etc/{name}.mp3')
mixer.music.play()
time.sleep(5)
if word == 'PAUSE':
mixer.music.pause()
time.sleep(5)
if word == 'STOP':
mixer.music.stop()
time.sleep(5)
if word == 'NEXT':
pass
if word == 'PREVIOUS':
pass
def update_button_text():
button_text.set("PAUSE")
if __name__ == '__main__':
# create application window
app = Tk()
# title
app.title("Music Player")
# geometry
app.geometry('383x121')
# background color
app.configure(bg='orange')
equation = StringVar()
window_1 = Label(app, textvariable=equation)
window_1.grid(columnspan=4, ipadx=100, ipady=10)
equation.set('music player')
window_2 = Entry(app, width=30)
window_2.grid(columnspan=4, ipadx=100, ipady=10)
window_2.configure(state='disabled')
window_2.grid_columnconfigure((0, 1, 2), uniform="equal", weight=1)
# Create buttons
button_text = StringVar()
button_text.set("PLAY")
button1 = Button(app, textvariable=button_text, fg='yellow', bg='purple',
command=lambda: press(button_text), height=2, width=1)
button1.grid(row=2, column=0, sticky="NSEW")
button2 = Button(app, text='STOP', fg='yellow', bg='purple',
command=lambda: press('STOP'), height=2, width=1)
button2.grid(row=2, column=1, sticky="NSEW")
button3 = Button(app, text='NEXT', fg='yellow', bg='purple',
command=lambda: press('NEXT'), height=2, width=1)
button3.grid(row=2, column=2, sticky="NSEW")
button4 = Button(app, text='PREVIOUS', fg='yellow', bg='purple',
command=lambda: press('PREVIOUS'), height=2, width=1)
button4.grid(row=2, column=3, sticky="NSEW")
# start the GUI
app.mainloop()
这是我遇到问题的部分:
button_text = StringVar()
button_text.set("PLAY")
button1 = Button(app, textvariable=button_text, fg='yellow', bg='purple',
command=lambda: press(button_text), height=2, width=1)
button1.grid(row=2, column=0, sticky="NSEW")
我之前使用过command=lambda: press('PLAY'),所以当我点击“播放”按钮时,它会转到def press('PLAY') 等等。但是现在我正在使用 StringVar 以便在单击后更改按钮文本,它不再起作用。我怎样才能使这项工作?
另外,当我运行代码并单击“播放”时,音乐确实会播放,但速度很慢。我试图先显示歌曲的名称,但似乎总是mixer.init() 部分比window_2.insert('end', name) 这部分运行得早。为什么会这样?
谢谢!
【问题讨论】: