I'm just trying to simulate a mouse click every second but once the first click starts, the program just completely halts and I have no idea why
The program will continue if I press CTRL+C but then it halts again after it clicks:
import pyautogui
import time
while True:
time.sleep(1)
print("Clicking")
pyautogui.click()
And it doesn't matter which mouse library I use to simulate the click, it always halts. It should be clicking every second without interruption. What's wrong?
The only reason i think it does so is because it clicks at some place where it is not supposed to(by default the position is your current mouse pointer), so the pyautogui.click() takes 2 parameters x,y try specifying the the exact coordinate and it should work. To find the coordinates of a position place your mouse pointer there and run pyautogui.position().
Related
I am currently trying to stop mouse clicks while my Script is running and still work with them.
If you are confused about the use case I will elaborate at the end of the question.
Currently I can get clicks like this:
import mouse
import time
def mouseHook(event):
if type(event) == mouse.ButtonEvent:
print(event)
mouse.hook(mouseHook)
while 1:
time.sleep(0.25)
But this still lets the clicks go through, how would I intercept them?
use case: simulate a monitor and while mouse is on that monitor send all movements, clicks and keypresses to MacBook (similar to Synergy, Mouse without Borders or Share Mouse)
The hook used by the application only 'hooks' into the process, which means it gets information from it, but can't insert or modify it's code.
For reference on windows that would use (https://learn.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms644988(v=vs.85))
The easiest way would be to have your application ignore the mouseclicks.
I was trying to make a bot for a game, which you can find here. You have to play games to get a tiny amount of bitcoin, like satoshis. Anyway, I as going to make a bot, but when I tried to click on the game window, it didn't do anything. Here is my code:
clicker.py
import pyautogui
while True:
x, y = pyautogui.position()
pyautogui.click(x, y, button='left')
I don't know what's going on, is it my code, or is it the website html? If it is the html, what should i change?
What may be happening is that when you run the program, your mouse clicks so fast that the site does not recognize the clicks. But anyways, how the program is supposed to stop? Your mouse will be clicking everywhere and you may not be able to close the Python window. Do something like this:
import pyautogui
from time import sleep
from threading import Thread
def click_function():
while True:
x, y = pyautogui.position()
pyautogui.click(x, y, button='left')
sleep(0.5) # an acceptable waiting time between one click and another
t = Thread(target=click_function)
t.daemon = True
t.start()
sleep(60)
# Here you put the amount of time you want the program
# to run, in seconds. This will ensure that the program
# stops sometime and you don't get stuck.
You can try adding sleep(n) at the beginning of the code. That is, you run the program, enter the site normally and point your mouse at the specific part where you want to click. Change the value of n to a considerable amount of time in seconds you can perform these tasks. If this doesn't work, you can try the Pynput module, which works similarly to PyAutoGUI.
I am trying to complete a simple GUI automation program that merely opens a web page and then clicks on a specific spot on the page every 0.2 seconds until I tell it to stop. I want my code to run and have its loop run infinitely until a keybind I specify breaks the loop (or entire program). I started out with the classic KeyboardInterrupt, which supposedly enables CTRL+C to exit a program. Here is my code:
import webbrowser, pyautogui, time
webbrowser.open('https://example.com/')
print('Press Ctrl-C to quit.')
time.sleep(5)
#pyautogui.moveTo(1061, 881)
try:
while True:
time.sleep(0.2)
pyautogui.click(1061,881)
except KeyboardInterrupt:
print('\nDone.')
Unfortunately, KeyboardInterrupt and using CTRL-C to exit do not seem to work for this script (likely due to the while loop?). This causes the loop to continue to run infinitely without a way to be stopped. So my questions are: why isn't the Keyboard Interrupt working? I've seen similar examples in other scripts. Additionally, if the KeyboardInterrupt doesn't work, is there a way I can code a simple keybind to exit the program/loop?
Use the following code
pyautogui.FAILSAFE = True
Then to stop, move the mouse to the upper-left corner of the screen
I suspect it may have something do to with you having a different active window than the script; when you use webbrowser, open a webpage, and click on it, it moves your active window to the webpage rather than the Python console. So ctrl+c will only produce a KeyboardInterrupt when the console is your active window. Your script may be in fact correct; but your active window is not on Python, so you would have to test it by clicking back into the Python console while the program runs.
To answer your comment: No, I do not know of any other "quick" way to do such a thing.
I'm late, but I can provide a solution which allows you to press CTRL + C to stop the program. You need to install the keyboard module and use keyboard.is_pressed() to catch when you press the keys you want as flag:
import keyboard
# You program...
while True:
time.sleep(0.2)
pyautogui.click(1061,881)
if keyboard.is_pressed("ctrl+c"):
break
You need to be careful though because the program will check if you have pressed the keys only when it executes the if statement. If your program runs for 10 seconds and you place the if at the end, you will only be able to exit every 10 seconds and for a very brief moment.
I also suggest to keep the keys pressed while you wait for the program to catch them to avoid missing the moment.
If you instead need to instantly terminate the program without having to always check if CTRL+C are pressed, you can place it in a process and kill it whenever you want. It's a bit overkill and it's not the recommended way, but if you really need it, here it is.
import pyautogui
import keyboard
import time
from multiprocessing import Process
def execute_program():
"""Long program which you want to interrupt instantly"""
while True:
pyautogui.click()
time.sleep(10)
if __name__ == '__main__':
# The failsafe allows you to move the cursor on the upper left corner of the screen to terminate the program.
# It is STRONGLY RECOMMENDED to keep it True
pyautogui.FAILSAFE = True
# Spawn and start the process
execute_program_process = Process(target=execute_program)
execute_program_process.start()
while True:
if keyboard.is_pressed('ctrl+c'):
execute_program_process.terminate()
break
print('\nDone.')
I have a Python 3.6.3 script that incorporates PyQt5. The GUI has a button that toggles play and pause of a video file. Pressing the spacebar also toggles play and pause. The button works fine all the time. The spacebar also works as intended, except at the very start of executing the script. I need to click some other event first (such as a button or slider bar) before the spacebar will correctly triggers the signal to pause or play the video. I want to start playing the video with the spacebar when the script starts up. Here is how I create the connections in the same __init__(self) function . As you can see, clicking on the button and pressing the spacebar both connect the signal to the same function (self.pauseVideo).
self.btnPause = QtWidgets.QPushButton(self.centralwidget)
self.btnPause.clicked.connect(self.pauseVideo)
self.spacebar = QShortcut(QKeySequence(Qt.Key_Space), self)
self.spacebar.activated.connect(self.pauseVideo)
Suggestions on how to get the spacebar to trigger the signal when the script first starts?
After a lot more searching, reassigning keyboard shortcuts (without success), etc., I found this post PyQt widget keyboard focus. I inserted
self.setFocusPolicy(Qt.StrongFocus)
into __init__(self) and it seemed to solve my problem! Now I'm just hoping it doesn't cause other issues.
I press this tkinter button, and the function bound to it finishes, but the button is stuck down. The rest of the gui is fine, its responsive, everything normal except for the button that is stuck down. I can even press the "stuck down" button again, and the bound function executes and finishes, but the button is still stuck down.
Sometimes the first few times I click the button it works fine and the button comes back up, but then after a few more clicks it will be stuck down. What could be causing this?
Here is the code for the button:
bf1=Button(self.canvas,text='F1',fg='tan1')
bf1.grid(row=4,column=1,sticky='nwse',columnspan=4)
bf1.bind('<Button-1>',self.f1)
I have found what is causing this, it is the fact that I am using the 'bind' function instead of the 'command'.
When I use this, the button sticks if you move the mouse off the button before the callback finishes (you can only realistically do this if you have a lot of work to do in the callback):
bf1=Button(self.canvas,text='F1',fg='tan1')
bf1.grid(row=4,column=1,sticky='nwse',columnspan=4)
bf1.bind('<Button-1>',self.f1)
But if you use the 'command', then there is no problem:
bf1=Button(self.canvas,text='F1',fg='tan1',command=self.f1)
bf1.grid(row=4,column=1,sticky='nwse',columnspan=4)
Is this a bug with tkinter's 'bind'?