For more technical content sharing, please click!
Preface
Pywinauto is a powerful Python library for automating the interface operations of Windows applications. Whether it is GUI testing, data acquisition or automation tasks, Pywinauto can provide a convenient solution. This article will introduce the basic usage of Pywinauto to help readers get started quickly and start automating Windows interface operations.
Install
The installation of pywinauto is similar to other libraries. It only requires one command, which is as follows:
pip install pywinauto
import module
Import the necessary modules of Pywinauto in the Python script, usually include Application
and findwindows
:
from pywinauto import Application
from pywinauto import findwindows
Start application
Start the target application using Application
the class's methods. start()
The following example shows how to start the Notepad application:
app = Application().start("notepad.exe")
Running the script will open a blank Notepad page, as shown below:
Connect to application window
Use findwindows
the module's find_windows()
functions to find the handle to the application window, then use Application
the class's connect()
methods to connect to the window:
handle = findwindows.find_windows(title='Untitled - Notepad', class_name='Notepad')[0]
app = Application().connect(handle=handle)
If an error occurs when searching for a handle, we can find the process ID of the application in the task manager, that is, PID
connect through the process ID. The method is as follows:
handle = findwindows.find_windows(process=14720)[0]
app = Application().connect(handle=handle)
Manipulating application window controls
Use the method Application
of the class window()
to obtain the application window object, and then operate the window through the properties and methods of the control. The following example demonstrates how to enter text in Notepad and save it:
window = app.window(title='Untitled - Notepad')
edit = window.Edit
edit.type_keys("曼城是冠军!")
window.menu_select("File->Save")
window.SaveAs.Edit.set_text("test.txt")
window.SaveAs.Save.click()
Handling dialog boxes and message boxes
For the pop-up dialog box and message box, you can use the methods Application
of the class Dialog
to operate. The following example shows how to handle the save confirmation dialog:
dialog = app.Dialog
dialog.SaveAs.Yes.click()
close application
When you're done, you can use Application
the class's kill()
methods to close the application:
app.kill()
Summarize
This article introduces the basic usage of Pywinauto, including steps such as installation, importing modules, starting applications, connecting to application windows, operating window controls, handling dialog boxes and message boxes, and closing applications. By mastering these basic concepts and techniques, readers can use Pywinauto to easily automate Windows interface operations and improve work efficiency. I hope this article will help you get started with Pywinauto!