首页 > 解决方案 > 如何从另一个函数中停止一个函数?

问题描述

我有一个程序,我希望它播放加载音乐,但完成后停止。

我在另一个线程(多线程)中考虑这个问题:

while True: 
    if Variables.StopMusic: 
        return
    else:
        playsound("blah.mp3", block=True)

但这只会在每次音乐结束时运行,所以它不能正常工作。

这是我当前的代码。

def commence():
    global photo #This is necessary because https://stackoverflow.com/a/16424553/9654083
    #AKA, It prevents the image from getting garbage collected
    mbox.showinfo("Commencing download...","Press OK to start...")
    url = Widgets.video.get()
    if url == "":
        mbox.showerror("Error", "Next time please type a URL.")
    load = Toplevel(window)
    load.geometry("1000x1000")
    photo = getPhoto(load)
    if Variables.audioSelect.get():
        playsound("/usr/share/youtube-dl-gui/loading_music.mp3", block=False)
    termf = Frame(load, height=50, width=200)
    termf.pack(side="bottom", fill="both", expand=YES) #https://stackoverflow.com/questions/37017472/python-tkinter-place-put-frame-to-the-bottom
    wid = termf.winfo_id()
    try:
        Popen(['xterm -into %d -geometry 200x50 -sb -e /bin/sh -c "youtube-dl %s;sleep 1;exit"' % (wid, url)], stdout=sstdout, stderr=sstdout, shell=True)
    except Exception as ename:
        mbox.showerror("ERROR!", "An error occured.")
        print(ename)

class Variables:
    audioSelect = IntVar()
    audioSelect.set(1)

class Widgets:
    video = Entry(window)
    text = Label(text="Please insert a URL.")
    audio = Checkbutton(variable=Variables.audioSelect, onvalue=True, offvalue=False, text="Add loading music?") #https://stackoverflow.com/a/16285194/9654083

Widgets.text.pack()
Widgets.video.pack()
Widgets.audio.pack()
Button(window, text="OK", command=commence).pack()

window.mainloop()

有没有像在python中杀死一个函数的东西?

标签: pythonpython-3.xtkinteraudio

解决方案


我最终使用了另一个允许暂停/停止的 Python 音乐库。

如果它对你有用,它是https://github.com/4br3mm0rd/mpyg321


推荐阅读