首页 > 解决方案 > Tkinter gui 不起作用鼠标和键盘模块

问题描述

我试图使用鼠标和键盘模块以及 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')

我应该怎么办?

标签: pythontkinterkeyboardmouse

解决方案


GUI 没有显示的原因是在代码命中之前mainloop()它进入了一个无限循环(while循环)并且它无法到达mainloop,因此窗口没有显示并且事件没有被处理。所以你应该做的是摆脱while. 一种方法是使用after()方法来模拟while.

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

这将每 100 毫秒重复一次该功能,您也可以将其减少到 1 毫秒。但请确保系统无法处理太多。


推荐阅读