Python / tkinter:标签中经过的时间/不断更新标签?

时间:2015-04-27 04:21:08

标签: python loops audio tkinter label

因此,我试图编写代码来显示音频文件的播放时间,通过不断循环和更新pyglet的经过时间方法中的标签文本。我可以抽出时间,但不会更新。想知道如何更新GUI上的标签以显示已用时间?时间循环接近底部,我提供了所有代码,以防万一。

from tkinter import *
from tkinter.filedialog import askopenfilename
import pyglet
import pyglet.media as media
from threading import Thread
from tkinter import colorchooser


#make player and it's methods global
global player
player = pyglet.media.Player();

app = Tk()
app.title("Music PYlayer")
app.geometry("600x200")
have_avbin = True 



#opens file 
def openFile():
    global f
    f =  filedialog.askopenfilename(filetypes = (("Mp3 files", "*.mp3"),("Wav files", "*.wav"),("All files","*.*")))

def aColor():
     mycolor = colorchooser.askcolor()
     color_name = mycolor[1] #  #to pick up the color name in HTML notation, i.e. the 2nd element of the tuple returned by the colorchooser
     app.configure(background=color_name)


#Creates menu bar for opening MP3s, and closing the program
menu = Menu(app)
file = Menu(menu)
file.add_command(label='Open', command=  openFile) # replace 'print' with the name of your open function
file.add_command(label='Background color', command = aColor)
file.add_command(label='Exit', command=app.destroy) # closes the tkinter window, ending the app
menu.add_cascade(label='File', menu=file)
app.config(menu=menu)

#Run each app library mainloop in different python thread to prevent freezing
def playMusic():
    global player_thread
    player_thread = Thread(target=real_playMusic)
    player_thread.start()

def stopMusic():
    global player_thread
    player_thread = Thread(target=real_stopMusic)
    player_thread.start()

#Play open file function attached to button
def real_playMusic():
    src=pyglet.media.load(f, streaming=False)
    global player
    player = pyglet.media.Player();
    player.queue(src)
    player.play()
    pyglet.app.run()

#Stop the music function
def real_stopMusic():
     player.pause()




#Play button creation
btnPlay = Button(app, text ="Play", command = playMusic)
btnPlay.place(x=75,y=100)


#Pause button creation
btnPause = Button(app)
btnPause.configure(text = "Stop", command = stopMusic)
btnPause.place(x=475,y=100)



#Time readout for track
def ReadOut():
    time2 = player.time
    i=0
    if i <= 0:
        nowPlaying=Label(app, text=time2)
        nowPlaying.grid()
        app.update_idletasks()





ReadOut()
app.mainloop() # keep at the end

1 个答案:

答案 0 :(得分:1)

我们将使用该函数告诉根tkinter实例(app)在一定时间后再次调用它,而不是使用循环更新它。 1}}方法。这样,它将以指定的频率无限期地运行。这类似于递归,但是每次运行时函数都会完成而不是等待递归调用结束,所以它不会遇到递归限制。

我们也只会创建after()一次,然后只需重新配置它。

改变这个:

Label

到此:

#Time readout for track
def ReadOut():
    time2 = player.time
    i=0
    if i <= 0:
        nowPlaying=Label(app, text=time2)
        nowPlaying.grid()
        app.update_idletasks()

ReadOut()
app.mainloop() # keep at the end