Python Tkinter gui不支持';t工作鼠标和键盘模块

Python Tkinter gui不支持';t工作鼠标和键盘模块,python,tkinter,keyboard,mouse,Python,Tkinter,Keyboard,Mouse,我试图使用鼠标和键盘模块以及tkinter作为gui制作一个自动点击器,并编写了这段代码 #Import import tkinter as tk import random as r8 import keyboard as kb import mouse as ms class Application(tk.Frame): def __init__(self, master=None): super().__init__(master) self.ma

我试图使用鼠标和键盘模块以及tkinter作为gui制作一个自动点击器,并编写了这段代码

#Import
import tkinter as tk
import random as r8
import keyboard as kb
import mouse as ms

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.master = master
        self.pack()
        self.create_widgets()
        self.joesd()

    def create_widgets(self):
        self.joe = tk.Frame(self)#main frame
        self.joe.pack(fill=tk.BOTH)
        self.lbl = tk.Label(self.joe, text='Example text', height=5, width=30)
        self.lbl.pack(side="top")# where the label will be located
        self.lb = tk.Label(self.joe, text='Example Text', height=5, width=35)
        self.lb.pack(side="top")# where the label will be located
    def joesd(self):
        while True:
            if kb.is_pressed('q') == True:
                ms.press('left')
                ms.release('left')

root = tk.Tk() 
app = Application(master=root)
app.mainloop()
然后我注意到gui从未出现,但如果我删除它,它将出现

    def joesd(self):
        while True:
            if kb.is_pressed('q') == True:
                ms.press('left')
                ms.release('left')

我该怎么办?

GUI没有显示的原因是,在代码点击
mainloop()
之前,它进入一个无限循环(
while
loop),它无法到达
mainloop
,因此窗口不显示,事件不被处理。因此,您应该做的是在的同时摆脱
。一种方法是使用
after()
方法模拟
while

def joesd(self):
    if kb.is_pressed('q'):
        ms.press('left')
        ms.release('left')
        
    self.after(100,self.joesd)

这将每100毫秒重复一次该功能,您也可以将其缩短为1毫秒。但是,请确保系统不会处理太多。

您不应该在tkinter应用程序中使用while循环。您可以使用
kb注册回调。请按\u键()

class Application(tk.Frame):
    def __init__(self, master=None):
        super().__init__(master)
        ...
        #self.joesd() # <- not necessary
        kb.on_press_key("q", self.on_key_press)

    ...

    def on_key_press(self, event):
        #print("q pressed", event)
        ms.press('left')
        ms.release('left')
        # above two lines can be replaced by ms.click('left')
类应用程序(tk.Frame):
def uuu init uuu(self,master=None):
超级()。\uuuu初始化\uuuuu(主)
...

#self.joesd()#在使用
tkinter
时,不应使用
键盘
/
鼠标
模块。相反,请查看
tkinter
事件绑定。
while
将停止
main循环
更新GUI。@lizzard tkinter事件绑定是否可以自动按键?@CoolCloud我删除了,但仍然没有任何内容happend@AmirTheDev我建议你看看tkinter教程。要使用tkinter的事件绑定,您需要传入一个函数,tkinter在发生诸如按下鼠标/键盘按钮之类的事情时调用该函数。虽然这确实有效,但这不是我所需要的,我需要不断单击该按钮。@CoolCloud确实给了我另一个成功的答案,但是感谢您花时间查看我的代码。@AmirTheDev如果您一直按“q”键,回调将继续执行。这可能会起作用,但它仍然不是我需要的,我想制作一个自动点击器,不需要人按任何东西。@AmirTheDev然后我想知道为什么您的代码一直在检查
kb。是否按下(“q”)