问题
Trying to practice Tkinter, Pyautogui and threading with a simple (or so I thought) auto clicker.
- It is supposed to open up a menu (check),
- then a choice of buttons (check),
- it opens up another window (check),
- and when you press F7 it starts clicking (not working)
This works fine without Tkinter
Here is code:
from tkinter import *
from pyautogui import *
from time import *
from threading import Thread as th
import keyboard
root = Tk()
key_loop = 1
k = ""
root.geometry("150x500")
def detect_key_def():
global k
while key_loop == 1:
if keyboard.is_pressed('f7'):
k = "f7"
elif keyboard.is_pressed("f8"):
k = "f8"
elif keyboard.is_pressed("f9"):
k = "f9"
detect_key = th(target=detect_key_def)
detect_key.start()
def clicker():
clicker = Tk()
root.geometry("300x300")
Label(clicker, text="Start - F7\n\nStop - F8").pack()
Button(clicker, text="Exit", command =clicker.destroy).pack()
if k == "f7":
click()
t.sleep(0.01)
elif k == "f8":
t.sleep(0.01)
clicker.mainloop()
Button(root, text="Auto Clicker", command=clicker).pack()
root.mainloop()
When I run the code the F7 starter does not work.
Any ideas?
回答1:
Ok so based on what you are trying to do with your code it is probably best to use after()
here instead of threading. Tkinter monitors all the key presses anyway so you can just bind the F7
button to the Toplevel window.
The below code will bind F7
to the clicker toplevel window. When you click in toplevel to give it focus you can use the F7
to start the auto clicking. I have it set to 1 clicks a second.
import tkinter as tk
from pyautogui import click
root = tk.Tk()
key_loop = 1
root.geometry("150x500")
def click_loop(event=None):
click()
root.after(100, click_loop)
def clicker():
clicker = tk.Toplevel(root)
root.geometry("300x300")
tk.Label(clicker, text="Start - F7\n\nStop - F8").pack()
tk.Button(clicker, text="Exit", command =clicker.destroy).pack()
clicker.bind("<F7>", click_loop)
tk.Button(root, text="Auto Clicker", command=clicker).pack()
root.mainloop()
来源:https://stackoverflow.com/questions/51729665/threads-and-tkinter-not-working-together