
👉 项目官网:https://www.python-office.com/ 👈

大家好,这里是程序员晚枫,正在all in AI编程实战。
今天教你怎么用代码控制和操作应用程序窗口!
1、启动应用程序
1 2 3 4 5 6 7 8 9 10 11 12 13
| import os
os.system('notepad')
os.system('start https://www.python-office.com')
os.system('start excel')
os.system('start winword')
|
2、关闭应用程序
1 2 3 4 5 6 7
| import os
os.system('taskkill /F /IM notepad.exe')
os.system('taskkill /F /IM excel.exe')
|
注意:Mac 用户用 killall 命令
3、检查程序是否运行
1 2 3 4 5 6 7 8 9 10
| import psutil
running = psutil.process_iter(['name']) excel_running = any('excel' in p.info['name'].lower() for p in running)
if excel_running: print('Excel正在运行') else: print('Excel未运行')
|
4、获取窗口信息
1 2 3 4 5 6 7 8
| import pyautogui
pyautogui.screenshot('screenshot.png')
width, height = pyautogui.size() print(f'屏幕分辨率: {width}x{height}')
|
5、模拟键盘和鼠标
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| import pyautogui
pyautogui.moveTo(100, 100, duration=0.5)
pyautogui.click()
pyautogui.doubleClick()
pyautogui.typewrite('Hello World')
pyautogui.press('enter')
|
6、实战案例:自动打开网页并截图
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import os import pyautogui import time
def open_and_screenshot(url, filename): """打开网页并截图""" os.system(f'start {url}') time.sleep(3) pyautogui.screenshot(filename) print(f'截图已保存: {filename}') os.system('taskkill /F /IM msedge.exe')
open_and_screenshot('https://www.python-office.com', '官网截图.png')
|
7、实战案例:自动填表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| import pyautogui import time
def auto_fill_form(): """自动填写表单""" fields = [ {'name': '张三', 'x': 200, 'y': 100}, {'name': '李四', 'x': 200, 'y': 150}, ] for field in fields: pyautogui.click(field['x'], field['y']) time.sleep(0.3) pyautogui.typewrite(field['name']) time.sleep(0.3) pyautogui.press('tab') print('表单填写完成!')
auto_fill_form()
|
8、常见问题
Q:坐标怎么确定?
A:用 pyautogui.position() 可以获取当前鼠标位置。
Q:Mac上能用吗?
A:可以,但部分功能可能需要调整。
Q:程序失控了怎么办?
A:移动鼠标到屏幕左上角(0,0),会自动中断程序。
9、下讲预告
学会了窗口管理,下一讲我们学 定时发送微信消息:用代码给自己发微信提醒。
敬请期待!
有问题欢迎加微信 python-office 进群交流~
程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。
🎓 AI 编程实战课程
想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!