when using pyautogui hotkeys dont seem to work

20 views Asked by At

when using hotkeys with pyautogui they dont work in any way. i have used to diffrent methods to get it to work. is there any other methods i should try or a fix for the methods im using?

pyautogui.keyDown(ctrl)
pyautogui.keyDown(t)
pyautogui.keyUp(ctrl)
pyautogui.keyUp(t)

NameError: name 'ctrl' is not defined is the error i get here.

pyautogui.hotkey('ctrl , t')

just doesnt work in anyway

can anyone help im trying to automate opening tabs and other things but i cant get it to work.

2

There are 2 answers

0
5rod On

pyautogui.hotkey() can be unreliable, and there is a much better way to automate opening and closing tabs. Instead, you can use webbrowser like this:

import webbrowser

webbrowser.open("https://example.com") #opens tab in default browser

webbrowser.open("https://example.com", new=1) #opens a tab in a second browser (if possible)

Unfortunately, webbrowser cannot close tabs. If you need to close tabs, and pyautogui.hotkey() doesn't work, you can try using keyboard:

import keyboard

keyboard.press_and_release('ctrl+w') #closes the tab
0
Willy On

https://pyautogui.readthedocs.io/en/latest/keyboard.html#keyboard-keys

From the docs:

The following are the valid strings to pass to the press(), keyDown(), keyUp(), and hotkey() functions:

Note the values in the array that follows are strings.

So pyautogui.keyDown('ctrl') is fine, but pyautogui.keyDown(ctrl) would throw an error, unless you had previously declared a variable named ctrl.