Reputation: 25
I was trying to make an auto clicker using Mouse and keyboard modules and tkinter as the gui and wrote this code
#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()
Then I noticed that the gui never appears but will appear if I removed
def joesd(self):
while True:
if kb.is_pressed('q') == True:
ms.press('left')
ms.release('left')
What should I do?
Upvotes: 2
Views: 318
Reputation: 47093
You should not use while loop in a tkinter application. You can register a callback using kb.on_press_key()
instead:
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')
Upvotes: 1
Reputation: 15098
The reason why GUI does not show up is that before the code hits mainloop()
it goes into a infinite loop(while
loop) and it cannot reach mainloop
and hence window does not show up and events are not processed. So what you should do is get rid of while
. One way is to use after()
method to emulate while
.
def joesd(self):
if kb.is_pressed('q'):
ms.press('left')
ms.release('left')
self.after(100,self.joesd)
This will repeat the function every 100 ms, you can reduce it to 1ms too. But make sure it is not too much for the system to handle.
Upvotes: 1