Reputation: 1
When I click on button 2 after pressing on button 1 it does not work.
I am making an auto clicker for fun, as a side project.
import tkinter as tk
from pynput.mouse import Button, Controller
import time
Height = 700
Width = 800
mouse = Controller()
flag = True
def click_function():
while flag == True:
time.sleep(.001)
mouse.click(Button.left, 1)
def endclick_function():
flag = False
root = tk.Tk()
canvas = tk.Canvas(root, height=Height, width=Width)
canvas.pack()
frame = tk.Frame(root,bg='black')
frame.place(relx=0.1, rely=0.1, relwidth=0.8, relheight=0.5)
button = tk.Button(frame, text="Start" , bg='white', fg='black', font=50, command=click_function)
button.place(relx=0, rely=0, relwidth=0.5, relheight=0.5)
button2 = tk.Button(frame, text="Stop" , bg='white', fg='black', font=50, command=lambda: endclick_function)
button2.place(relx=.5, rely=0, relwidth=0.5, relheight=0.5)
label = tk.Label(frame, text='Time to Sleep:', bg='white', font=50)
label.place(relx=0, rely =0.5, relwidth=0.5, relheight=0.25)
label2 = tk.Label(frame, text='How many times to click:', bg='white', font=50)
label2.place(relx=0, rely =0.75, relwidth=0.5, relheight=0.25)
entry = tk.Entry(frame, bg='white')
entry.place(relx=0.5, rely =0.5, relwidth=0.5, relheight=0.25)
entry2 = tk.Entry(frame,text='Time to Sleep(ms):', bg='white')
entry2.place(relx=0.5, rely =0.75, relwidth=0.5, relheight=0.25)
root.mainloop()
Upvotes: 0
Views: 57
Reputation: 885
you have to declare flag global if you want to change it
also as Joe Ferndz pointed out, the flag is never set back to True
def click_function():
global flag
flag = True # of course, only if you want to use clicker more than once
while flag == True:
time.sleep(.001)
mouse.click(Button.left, 1)
def endclick_function():
global flag
flag = False
Something I just noticed
in button2
, command=lambda:end_f
remove lambda
this is basically saying
def l():
return end_f
button2['command'] = l
and since the command (l
) is executed at the click on the button,
it only returns the function, does not execute it
Upvotes: 1
Reputation: 8508
When you click the first button, the flag is set to True. However, when you click on second button, the flag gets set to False. Later when you come back to first button, the flag is False so it never goes into the while loop.
Do you want to try and implement this an alternate way?
def click_function():
while flag == True:
time.sleep(.001)
mouse.click(Button.left, 1)
def endclick_function():
flag = False
Upvotes: 0