How to use python to control the computer
This article introduces the knowledge of "how to use python to operate a computer". In the operation of practical cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
1. Environment
Python
IDLE
3.8
Third-party library pyautogui
Among them, the pyautogui installation method is very simple:
Pip install pyautogui
Then enter the following in Python:
Import pyautogui
If there is no wrong report, it will be a success.
two。 Use pyautogui to control your computer mouse
Looking at the name, you can see that this is a tool to automatically control gui, but more people use it to control computers. If you are interested, you can try to make a tutorial tool.
First import the library:
Import pyautogui as pg
You can use the position method to obtain the current mouse coordinates (the origin is the upper-left corner):
Pos = pg.position ()
So what's the use of getting the coordinates? We can get him to click:
# Click pg.click () at the current location
Of course, you can also specify a location:
# Click pg.click at (10) (10)
Specify the key:
# right click # the value is left,right,middlepg.click (button='right')
Then someone must have asked, can I double-click?
Some people said, "Click on the same location twice."
But there is a simpler way:
Pg.doubleClick ()
You can even click multiple times and set the interval:
# Click twice with an interval of 0.5s pg.click (clicks=2, interval=0.5)
Sometimes you may want to drag and drop documents. What should I do? Pyautogui has also packed it for you:
# drag to (10j.90) pg.dragTo (10j.90)
In fact, this library is also useful in crawlers, which encapsulates a scroll function:
# positive and negative pg.scroll
You can also take a screenshot. The returned value is the Image object of the PIL library:
Pg.screenshot ()
You can input screenshot coordinates:
# left, upper and right coordinates pg.screenshot (region= (100,100,300,400))
You can even compare whether the image appears on the screen:
Pg.locateOnScreen ('kk.png') 3. Use pyautogui to control your computer keyboard
Type with press:
Pg.press ('Hello Worldwaters, interval=0.5)
If you want to enter a feature button, refer to the following:
You can use hotkey to implement key combinations:
Pg.hotkey ('ctrlleft',' c') 4. Pop-up window
This is very easy to use, nothing to make a virus for a friend.
Text + ok:
Pg.alert ('I hear you have the virus?')
Text + ok+cancel:
Pg.confirm ('caught the virus again')
Text input box, return the input, do not write on the None:
This is the end of pg.prompt ('here comes the virus again'), "how to use python to operate a computer". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!