这不知何故冻结了我的整个程序,我不确定为什么?

This somehow freezes my whole program and Im not sure why?

所以我 运行 线程上的所有内容和 runnot run 按预期工作但 running 不打印,我尝试在

中调用它
        status["text"]="Working"
        print("run")
        process()

但这只是冻结了我的整个程序,我也尝试在最后输入 root.after 但仍然冻结了所有内容。这里的任何方式都是我正在谈论的部分的片段。

def keyStart():
    global run
    run = True
    while run == True:
        status["text"]="Working"
        print("run")
        process()



def keyStop():
    global run
    run = False
    if run == False:
        status["text"]="Not Working"
        print("not run")

        
buttonStart = Button(root, text="Start", command=keyStart)
buttonStart.grid(columnspan=1, column=0, row=3)
buttonStop = Button(root, text="Stop", command=keyStop)
buttonStop.grid(columnspan=1, column=1, row=3)



            
def process():
    global run
    while run == True:
        print("running")

与所有 GUI 框架一样,Tkinter 是事件驱动的。您的 GUI 调用实际上不进行任何绘图。他们只是发了信息。有一个主循环 (root.mainloop) 用于获取和分派消息以进行处理。只要消息处理程序是 运行,它就无法返回主循环,并且不会处理更多消息。

这就是问题所在。您按下按钮将触发您的 keystart,它会调用 autofisher,而 autofisher 永远不会 returns。它运行一个 100% 紧密的 CPU 循环。因为您没有返回到主循环,所以 GUI 被冻结。不再处理 activity。

你不应该混用 tkinterkeyboardtkinter 有自己的键盘处理能力,可以很好地与框架的其余部分配合使用。您需要扔掉 keyboard 模块,并使用 tkinter bind 调用将回调与击键相关联。

https://python-course.eu/tkinter/events-and-binds-in-tkinter.php https://www.pythontutorial.net/tkinter/tkinter-event-binding/