首页 > 解决方案 > 当用户单击“继续”时,tkinter 窗口在播放音效后冻结

问题描述

当我在用户通过测试后尝试播放“yay”音效时,我会显示学分。不过考虑到有些用户不耐烦不想看,我做了一个tkinter窗口来显示是否看的选项。但是当用户点击“继续”时,tk 窗口冻结(冻结窗口),过一会又正常了。
这可能不是一个很大的问题。但是如果编译成exe文件,可能会导致无预警突然退出,用户体验不好。那么有什么办法可以阻止冻结呢?
这是窗口冻结的代码的一部分。

class Success(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Yay! You have passed my chemistry challenge! Would you like to continue?",
                         font=LARGE_FONT)
        label.pack(pady=10, padx=10)
        button1 = tk.Button(self, text="Continue", command=lambda: [controller.show_frame(Credits), success1()])
        button1.pack()
        button2 = tk.Button(self, text="Quit", command=lambda: controller.destroy())
        button2.pack()

    def correspondingBehavior(self, choice):
        print(choice)


class Credits(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self,
                         text="Credits: bababa..." )
        label.pack(pady=10, padx=10)
        button1 = tk.Button(self, text="Quit", command=lambda: controller.destroy())
        button1.pack()

    def correspondingBehavior(self, choice):
        print(choice)

在编写代码之前,我已经导入playsound了模块并定义了如下success1()函数:

def success1():
    playsound("D:/Personal/Game/Yah.mp3")

标签: pythontkinter

解决方案


不要让它阻塞主线程:

def success1():
    playsound("D:/Personal/Game/Yah.mp3", block=False)

或者您可以创建一个新的thread,但以后可能会崩溃tkinter


推荐阅读