python-3.x Tkinter GUI冻结,使用线程,然后遇到运行时错误:线程只能启动一次

relj7zay  于 2023-01-14  发布在  Python
关注(0)|答案(1)|浏览(138)

请帮帮忙

def change_flag(top_frame, bottom_frame, button1, button2, button3, button4, controller):
    global counter, canvas, my_image, chosen, flag, directory
    canvas.delete('all')
    button5['state'] = DISABLED
    counter += 1

    chosen, options_text = function_options()
    right_answer_flag = get_right_answer_flag(chosen, options_text)
    #pdb.set_trace()

    try:
        location = directory + chosen + format_image
    except:
        controller.show_frame(PlayAgainExit)
        
    my_image = PhotoImage(file=location)
    canvas.create_image(160, 100, anchor=CENTER, image=my_image)

    button1["text"] = options_text[0]
    button2["text"] = options_text[1]
    button3["text"] = options_text[2]
    button4["text"] = options_text[3]

    button1['state'] = NORMAL
    button2['state'] = NORMAL
    button3['state'] = NORMAL
    button4['state'] = NORMAL

##############

        button5 = Button(
            next_frame,
            width=20,
            text="next",
            fg="black",
            #command=lambda: change_flag(top_frame,bottom_frame,button1,button2,button3,button4,controller))
            command=Thread(target=change_flag, args =(top_frame,bottom_frame,button1,button2,button3,button4,controller)).start)
            
        button5.pack(side=RIGHT, padx=5, pady=5)

你好,
我不希望GUI冻结,所以我使用button5的线程,但它给我的运行时错误“你可以启动线程只有一次”这是正确的。但我应该如何解决这个问题?
谢谢你的帮助,阿沛

jaql4c8m

jaql4c8m1#

command=Thread(target=change_flag, args=(top_frame,bottom_frame,button1,button2,button3,button4,controller)).start

创建thread对象的一个示例,将该示例的start函数的引用传递给command选项,如下所示:

# create an instance of the thread object
t = Thread(target=change_flag, args=(top_frame,bottom_frame,button1,button2,button3,button4,controller))
# pass the start function of the thread object to command option
button5 = Button(..., command=t.start)

因此,当单击按钮时,它启动线程。当再次单击按钮时,再次启动相同的线程示例,这是不允许的。
您可以使用lambda,以便在单击按钮时创建并启动线程对象的新示例:

button5 = Button(..., command=lambda: Thread(target=change_flag, args=(top_frame,bottom_frame,button1,button2,button3,button4,controller)).start())

相关问题