pyautogui does not click based on slider/scale values in Tkinter - python

How I can make pyautogui click based on scale value in Tkinter ?
For example if the scale value is 10 the click delay (with pyautogui.PAUSE) should be of 0.1 it represent 10 clicks per second and if the scale value is 15 the delay should be of 0.15 => 15 clicks per second.
The problem clicks are not activated depending on the scale value
I also can't put root.mainloop() anywhere else than in the While True loop although I would have liked to put it at the very end of the program but in this case I would have to replace while True by "while "normal" == root.state()" (to stop the loop as soon as the Tkinter window closes) which doesn't work either
The code :
import mouse
import threading
import pyautogui
from tkinter import *
from tkinter import ttk
root = Tk()
root.geometry('500x400')
bovar = IntVar()
def func(*args):
if bovar.get() == 10:
pyautogui.PAUSE = 0.1
elif bovar.get() == 11:
pyautogui.PAUSE = 0.11
elif bovar.get() == 12:
pyautogui.PAUSE = 0.12
elif bovar.get() == 13:
pyautogui.PAUSE = 0.13
elif bovar.get() == 14:
pyautogui.PAUSE = 0.14
else:
pyautogui.PAUSE = 0.15
scale = Scale(root,orient=HORIZONTAL,from_=10,to=15,variable=bovar,command=func)
label = Label(root,text='CPS:')
label.pack(side=TOP)
scale.pack()
func()
root.mainloop()
def repeat_function(kill_event):
while not kill_event.is_set():
pyautogui.click()
while True:
kill_event = threading.Event()
new_thread = threading.Thread(target=lambda: repeat_function(kill_event))
mouse.on_button(new_thread.start, (), mouse.RIGHT, mouse.DOWN)
mouse.on_button(kill_event.set, (), mouse.RIGHT, mouse.UP)
mouse.wait(mouse.RIGHT, mouse.UP)
mouse.unhook_all()

root.mainloop() starts an infinite loop that waits for actions on the tkinter window and responds to them. Thus, any code you write under this call isn't going to execute until you close tkinter. If you want something to run simultaneously with this tkinter loop, it will have to run in another thread. Your logic of determining PAUSE is also a little flawed. A pause of 0.15 seconds doesn't mean it will click 15 times per second, but 1/0.15 times.
import mouse
import threading
import pyautogui
from tkinter import *
from tkinter import ttk
def convert_to_pause(clicks_per_second):
clicks_per_second = min(clicks_per_second, 15)
return 1 / clicks_per_second
def repeat_function(kill_event, int_var):
while not kill_event.is_set():
pyautogui.PAUSE = convert_to_pause(int_var.get())
pyautogui.click()
def hotkey_thread_loop(int_var):
# The loop you already have, we just need to run it in a separate thread
# We pass it the IntVar from the Scale so that it can dynamically read its value
while True:
kill_event = threading.Event()
# Here we also pass the IntVar to access its value in the new thread
new_thread = threading.Thread(target=lambda: repeat_function(kill_event, int_var))
mouse.on_button(new_thread.start, (), mouse.RIGHT, mouse.DOWN)
mouse.on_button(kill_event.set, (), mouse.RIGHT, mouse.UP)
mouse.wait(mouse.RIGHT, mouse.UP)
mouse.unhook_all()
# Start the main program
if __name__ == "__main__":
# Set up all tkinter stuff
root = Tk()
root.geometry('500x400')
bovar = IntVar()
scale = Scale(root,orient=HORIZONTAL,from_=10,to=15,variable=bovar,command=func)
label = Label(root,text='CPS:')
label.pack(side=TOP)
scale.pack()
# Create the thread to manage hotkey pressing and start it
# Set daemon=True to have it terminate when main program ends
hotkey_thread = threading.Thread(target=lambda: hotkey_thread_loop(bovar),
daemon=True)
hotkey_thread.start()
# Start the tkinter application, the ininite loop
root.mainloop()
# Any code put here (below mainloop()) will not execute while tkinter runs,
# don't try to implement more logic here

Related

Tkinter- How to stop a loop that is in another file with a stop button?

I want to stop a loop when I press a button. If I do it all in the same files I don´t have a problem but when I put the loop as a routine from another file It doesn´t work and I don´t know why. I hope you can help me! Thanks!!
First of all, this is subroutine.py, the file where is the loop allocated
subroutine.py
def routine (pressed):
while True:
print ("hello")
if pressed== 1:
break #Break while loop when stop = 1
And this is the "main" file
import tkinter as tk
import threading
import subroutine
pressed = 0
def Start_Scan():
global pressed
pressed = 0
# Create and launch a thread
t = threading.Thread (target = subroutine.routine (pressed))
t.start()
def Stop():
global pressed
pressed = 1
#main
master = tk.Tk()
app = tk.Frame(master)
app.grid()
start = tk.Button(app, text="Start Scan",command=Start_Scan)
stop = tk.Button(app, text="Stop",command=Stop)
start.grid()
stop.grid()
app.mainloop()
I use thread and a global variable, I thought about not using a global variable but I didn't find a way for the two threads to communicate that was not blocking. Thanks!!
You can use threading.Events to pass a flag between the main thread and the worker thread
# main.py
stop_event = threading.Event()
def Start_Scan():
# Create and launch a thread
t = threading.Thread (
target=subroutine.routine,
args=(stop_event,) # pass the Event object to the worker target
)
t.start()
def Stop():
stop_event.set()
Just update your subroutine to keep an eye on that event
# subroutine.py
def routine(stop_event):
while not stop_event.is_set(): # loop until the Event is 'set'
print ("hello")

python thread data manipulation

I am trying to manipulate some data in a thread from the main function. The issue I am facing about modifying some of the variables which are part of the function which is running on a thread.
So I am trying to run a Tkinter based GUI loop in a thread to ensure it is always running. And want to modify some of the label corresponding to the status in the main function execution. I am facing an issue where it is unable to locate the label variables in the main loop as it is part of the function running on the thread.
Below is a simplified psuedo code for that approach. Please suggest if this a correct way to the above task or is there is any better and efficient way.
import threading
def thread_func():
i = 0
while True:
print('i from thread: ', i)
if __name__ == '__main__':
t = threading.Thread(target=thread_func)
t.start()
while True:
i += 1
Actual scaled down simplified code
import threading
import tkinter as tk
def gui():
window = tk.Tk()
label = tk.Label(text='On')
label.pack()
window.mainloop()
if __name__ == '__main__':
t = threading.Thread(target=gui)
t.start()
while True:
label['text'] = 'Active'
Error:
Traceback (most recent call last):
File "test.py", line 17, in <module>
label['text'] = 'Active'
NameError: name 'label' is not defined
Is there a better way to keep the tkinter gui always on and perform some task in the loop?
Using class and threading:
import tkinter
class Test(tkinter.Label):
x = False
def __init__(self):
super().__init__()
self.pack()
self['text'] = 'On'
def gui(self):
if not self.x:
self['text'] = 'Active'
self.mainloop()
else:
self.mainloop()
if __name__ == '__main__':
label = Test()
while isinstance(label, Test):
t = threading.Thread(target=label.gui())
t.start()
When you write code of label there then you will get error because when program start it starts from creating thread, that thread will only end when tkinter window is close and same for previous thread_fuc code. And you wrote the label code after tkinter window is closed.
The above issue will be solved by doing this :
import threading
def thread_func():
while True:
print('i from thread: ', i)
def tt():
global i
while True:
i += 1
if __name__ == '__main__':
i=0
t = threading.Thread(target=thread_func)
t.start()
yt = threading.Thread(target=tt)
yt.start()
Making i global and running 2 function parallely. We have to global because we can't use the variable of one function to another. And additionally we are running 2 function in 2 thread.
And for your tkinter file as #TheLizzard suggest, you can use .after insted of using thread in tkinter if you want to change content constantly/want to use loop.
Here's the basic example how you can implement it:
import random
import tkinter as tk
app = tk.Tk()
app.geometry("200x220")
label = tk.Label(app, text="0")
label.pack()
def change(b=0):
if b < 30:
a = random.randrange(1, 7, 1)
label.config(text=a)
app.after(100, change, b+1)
b1 = tk.Button(app, text="Get New Number", command=change)
b1.pack()
app.mainloop()
For more explanation about it you may visit here.

Tkinter messagebox doesnt disappear after press 'ok/confirmation

I wrote a little script to track the battery capacity of my device. Mostly for learning Python.
I decided to use a loop to recognize low capacity. So far it is okay, but when I use a tkinter messagebox, the window does not disappear after I confirm the warning.
import os
from time import sleep
import tkinter as tk
from tkinter import *
from tkinter import messagebox
stat = "/sys_vars/status"
plugged = "PLUGGED"
unplugged = "UNPLUGGED"
batfile = "/sys_vars/capa"
root = tk.Tk()
root.withdraw()
def read(sysfile):
with open(sysfile, "r") as f:
return f.read()
def loopcheck():
plug = str(read(stat).strip())
bat = int(read(batfile))
if plug == plugged:
sleep(2)
if plug == unplugged and 6 <= bat <= 15:
messagebox.showwarning("Alert!","Battery Low!\nCharging Required!")
sleep(2)
if plug == unplugged and bat <= 5:
messagebox.showwarning("ALERT!","Battery ULTRA Low!\nCharging Required!")
sleep(2)
if __name__ == "__main__":
messagebox.showinfo("Running!","Battry Status Tracker is now running on machine")
while True:
loopcheck()
I expect that I confirm the warning and then the message show after the amount of seconds.
The variables and the short sleep-timer in the example are there for tests.
Instead of while True and sleep(2) you should use root.after(2000, loopcheck) to run function in delay. It will not block root.mainloop() which has to run all time to get key/mouse events from system, send events to widgets and redraw windows/widgets.
I don't have these /sys_vars to test it but it could be something like this:
import tkinter as tk
from tkinter import messagebox
stat = "/sys_vars/status"
plugged = "PLUGGED"
unplugged = "UNPLUGGED"
batfile = "/sys_vars/capa"
def read(sysfile):
with open(sysfile, "r") as f:
return f.read()
def loopcheck():
plug = str(read(stat).strip())
bat = int(read(batfile))
if plug == unplugged:
if 6 <= bat <= 15:
messagebox.showwarning("Alert!","Battery Low!\nCharging Required!")
elif bat <= 5:
messagebox.showwarning("ALERT!","Battery ULTRA Low!\nCharging Required!")
root.after(2000, loopcheck)
if __name__ == "__main__":
root = tk.Tk()
root.withdraw()
messagebox.showinfo("Running!","Battry Status Tracker is now running on machine")
root.after(2000, loopcheck)
root.mainloop()

I want to toggle a real pushbutton and display it on tkinter GUI

I want to toggle a pushbutton and show its changes on a label using tkinter.
If I press the button it shows "on" on the label and when I press again it shows "off" on the label
So I try these codes and If I'm trying the wrong code please help me write the correct using tkinter.
I have a problem in combining this code
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(22,GPIO.IN,up_down=GPIO.PUD_UP)
while(1):
if GPIO.input(22)==1:
if bs == False :
x.set("on")
bs=True
sleep(0.5)
else:
x.set("off")
bs=False
sleep(0.5)
This works okay but I want to connect it to a GUI label to print on it on or off.
Here is the tkinter code
import tkinter.*
root = tk()
x = StringVar()
s=Label(root,textvariable=x)
s.grid(column=0,row=0)
root.mainloop()
When I try to combine it I make it like this
from Tkinter import *
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.IN)
b=False
def check_button1():
if GPIO.input(7)== 1:
if b == False :
labelText1.set("on")
print"on"
b=True
time.sleep(0.5)
else:
labelText1.set("off")
print"off"
b=False
time.sleep(0.5)
mamdouh.after(10,check_button1)
mamdouh = Tk()
labelText1 = StringVar()
x1 = Label(mamdouh,textvariable=labelText1)
x1.config(font=('Helvetica',25,'bold'))
x1.grid(row=0,column=0)
mamdouh.title("mamdouh")
mamdouh.geometry('1200x700')
mamdouh.after(10,check_button1)
mamdouh.mainloop()
but it didn't works it keeps blank every time I press the push button actually If it works well I will put 17 push button
I think that the problem is in placing this if statment on the right place and placing the b variable in it's right place and I think also there is a problem between this if statment and tkinter because I tried this code wich works perfect but it is not toggling the push button so I want to change this lets add this code here also :
from Tkinter import *
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BOARD)
GPIO.setup(7,GPIO.IN)
def check_button1():
if(GPIO.input(7) == GPIO.LOW):
labelText1.set("on")
else:
labelText1.set("off")
mamdouh.after(10,check_button1)
mamdouh = Tk()
labelText1 = StringVar()
x1 = Label(mamdouh,textvariable=labelText1)
x1.config(font=('Helvetica',25,'bold'))
x1.grid(row=0,column=0)
mamdouh.title("mamdouh")
mamdouh.geometry('1200x700')
mamdouh.after(10,check_button1)
mamdouh.mainloop()
So how I can make this toggle push button on an Label?
Your problem is recognizing button down and button up events. Your OS mouse driver does this for your mouse buttons. If your GPIO module does not do this for you, you will have to detect these events by comparing the current state to the previous state. (I am ignoring here any possible need to 'de-bounce' the button.) You are sort of trying to do this with the time.sleep(.5) calls, but do not use time.sleep in gui code.
Your driver should be self-contained and independent of any tk widgets other than the root needed for .after. For multiple buttons, you will need your own GPIOButton class. Your code that works is a starting point. Tkinter allows you to tie a command to button-up events. Your class init should similarly take up and or down event commands (callbacks).
Here is something untested that might get you started.
class GPIOButton:
def __init__(self, master, buttons, command_down=None, command_up=None):
self.master = master
self.buttons = buttons
self.command_down = command_down
self.command_up = command_up
GPIO.setmode(GPIO.BOARD)
for button in buttons:
GPIO.setup(button, GPIO.IN)
self.state = [GPIO.HIGH] * len(buttons) # best initial value?
self.check_buttons() # or call this elsewhere
def check_buttons(self):
for i, button in enumerate(self.buttons):
oldstate = self.state[i]
newstate = GPIO.input(button)
if oldstate != newstate:
self.state[i] = newstate
command = (self.command_down if newstate==GPIO.LOW
else self.command_up)
command(button)
self.master.after(10, self.check_button)
Let me preface my answer with a disclaimer—I don't have a Raspberry Pi, so couldn't verify this works with the real thing. For testing I used a proxy class that simulates random button pressing. You may have to adjust the DELAY value depending on how fast the GPIO interface works.
However, I have put commented-out code in near the top showing what I think you would need to use based on of doing so in your code.
try:
import Tkinter as tk
import tkFont
except ImportError: # Python 3
import tkinter as tk
import tkinter.font as tkFont
#import RPi.GPIO as GPIO
#
#GPIO.setmode(GPIO.BOARD)
#
#class GPIOButton(object):
# """ Encapsulates GPIO button interface. """
# def __init__(self, pin):
# self.pin = pin
# self.status = 0
# GPIO.setup(pin, GPIO.IN)
#
# def update_status(self):
# self.status = GPIO.input(pin) == GPIO.LOW
### Proxy class since I don't have a Rasperry Pi. ###
import random
class GPIOButton(object):
def __init__(self, pin):
self.pin = pin
self.status = 0
def update_status(self):
if not random.randint(0, 99) % 20: # occassionally toggle status
self.status = not self.status
class App(tk.Frame):
STRIDE = 8
DELAY = 100 # delay in millsecs between button status updates
def __init__(self, gpio_buttons, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.gpio_buttons = gpio_buttons
self.create_widgets()
self.after(self.DELAY, self.update_buttons, self.DELAY) # start updates
def create_widgets(self):
self.btn_font = tkFont.Font(family="Helvetica", size=12, weight='bold')
self.gui_buttons = []
for i, button in enumerate(self.gpio_buttons):
is_pressed = tk.BooleanVar()
is_pressed.set(False)
radiobutton = tk.Radiobutton(self,
text=format(i+1, '02d'),
font=self.btn_font,
value=True,
variable=is_pressed,
relief=tk.RIDGE)
row, col = divmod(i, self.STRIDE)
radiobutton.grid(column=col, row=row)
self.gui_buttons.append(is_pressed)
def update_buttons(self, delay):
for i, gpio_button in enumerate(self.gpio_buttons):
previous_status = gpio_button.status
gpio_button.update_status()
if gpio_button.status != previous_status:
self.gui_buttons[i].set(gpio_button.status)
self.after(delay, self.update_buttons, delay) # rinse and repeat
gpio_buttons = [GPIOButton(pin) for pin in range(16)]
app = App(gpio_buttons)
app.master.title('Rasberry Pi Buttons')
app.mainloop()
Here's what the simulation looks like running on my Windows computer:

Display count variable from background task in main task (Tkinter GUI)

I am trying to display a count variable from a background task in the main task which is my tkinter GUI. Why? I want to display that the long time taking background task is performing and later use this count variable to visualize it with a progress bar.
My problem is, that even when using a Queue, I am not able to display the count variable. Maybe I've got problems in understanding python and its behaviour with objects and/or threads.
import threading
import time
import Queue
import Tkinter as Tk
import Tkconstants as TkConst
from ScrolledText import ScrolledText
from tkFont import Font
import loop_simulation as loop
def on_after_elapsed():
while True:
try:
v = dataQ.get(timeout=0.1)
except:
break
scrText.insert(TkConst.END, str(v)) # "value=%d\n" % v
scrText.see(TkConst.END)
scrText.update()
top.after(100, on_after_elapsed)
def thread_proc1():
x = -1
dataQ.put(x)
x = loop.loop_simulation().start_counting()
# th_proc = threading.Thread(target=x.start_counting())
# th_proc.start()
for i in range(5):
for j in range(20):
dataQ.put(x.get_i())
time.sleep(0.1)
# x += 1
time.sleep(0.5)
dataQ.put(x.get_i())
top = Tk.Tk()
dataQ = Queue.Queue(maxsize=0)
f = Font(family='Courier New', size=12)
scrText = ScrolledText(master=top, height=20, width=120, font=f)
scrText.pack(fill=TkConst.BOTH, side=TkConst.LEFT, padx=15, pady=15, expand=True)
th = threading.Thread(target=thread_proc1)
th.start()
top.after(100, on_after_elapsed)
top.mainloop()
th.join()
In thread_proc1() I want to get the value of the counter of background task. This is the background task:
import time
class loop_simulation:
def __init__(self):
self.j = 0
# self.start_counting()
def start_counting(self):
for i in range(0, 1000000):
self.j = i
time.sleep(0.5)
def get_i(self):
return str(self.j)
The reason the count variable isn't being displayed is due to the
x = loop.loop_simulation().start_counting()
statement in thread_proc1(). This creates a loop_simulation instance and calls its start_counting() method. However, other than already inserting a -1 into the dataQ, thread_proc1() doesn't do anything else until start_counting() returns, which won't be for a long time (500K seconds).
Meanwhile, the rest of your script is running and displaying only that initial -1 that was put in.
Also note that if start_counting() ever did return, its value of None is going to be assigned to x which later code attempts to use with: x.get_i().
Below is reworking of your code that fixes these issues and also follows the PEP 8 - Style Guide for Python Code more closely. To avoid the main problem of calling start_counting(), I changed your loop_simulation class into a subclass of threading.Thread and renamed it LoopSimulation, and create an instance of it in thread_proc1, so there are now two background threads in addition to the main one handling the tkinter-based GUI.
import loop_simulation as loop
from ScrolledText import ScrolledText
import threading
import Tkinter as Tk
import Tkconstants as TkConst
from tkFont import Font
import time
import Queue
def on_after_elapsed():
# removes all data currently in the queue and displays it in the text box
while True:
try:
v = dataQ.get_nowait()
scrText.insert(TkConst.END, str(v)+'\n')
scrText.see(TkConst.END)
except Queue.Empty:
top.after(100, on_after_elapsed)
break
def thread_proc1():
dataQ.put(-1)
ls = loop.LoopSimulation() # slow background task Thread
ls.start_counting()
while ls.is_alive(): # background task still running?
for i in range(5):
for j in range(20):
dataQ.put(ls.get_i())
time.sleep(0.1)
time.sleep(0.5)
dataQ.put('background task finished')
top = Tk.Tk()
dataQ = Queue.Queue(maxsize=0)
font = Font(family='Courier New', size=12)
scrText = ScrolledText(top, height=20, width=120, font=font)
scrText.pack(fill=TkConst.BOTH, side=TkConst.LEFT, padx=15, pady=15,
expand=TkConst.YES)
th = threading.Thread(target=thread_proc1)
th.daemon = True # OK for main to exit even if thread is still running
th.start()
top.after(100, on_after_elapsed)
top.mainloop()
loop_simulation.py module:
import threading
import time
class LoopSimulation(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.daemon = True # OK for main to exit even if instance still running
self.lock = threading.Lock()
self.j = 0
start_counting = threading.Thread.start # an alias for starting thread
def run(self):
for i in range(1000000):
with self.lock:
self.j = i
time.sleep(0.5)
def get_i(self):
with self.lock:
return self.j

Categories