使用Tkinter时线程停止中的循环

2024-10-04 01:23:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下。这意味着当用户单击CTRL+X时弹出一个tkinter窗口,当按下CTRL+a时关闭该窗口。问题是当窗口在打开后关闭时,lookForKeys中的while循环停止

import tkinter as tk
from threading import Thread
import keyboard as k

running = False


def main():
    global root
    print('Opening...')
    root = tk.Tk()
    root.geometry("340x740+1550+50")
    root.title('Custom Mic')
    root.resizable(0,0)    
    root.attributes('-topmost', True)
    root.update()

    root.mainloop()

def closeOverlay():
    print('Closing...')
    root.destroy()
    root.quit()


def openOverlay():
    global overlayThread
    print('Opening...')
    overlayThread = Thread(target = main)
    overlayThread.start()

def lookForKeys():
    global running

    while True:
        print(running)
        if k.is_pressed("ctrl+x") and running == False:
            running = True
            openOverlay()

        if k.is_pressed("ctrl+a") and running == True:
            running = False
            closeOverlay()

if __name__ == "__main__":
    mainThread = Thread(target = lookForKeys)
    mainThread.start()

任何帮助都是感激的


Tags: importfalsetrueifmaintkinterdefroot