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

github star

大家好,这里是程序员晚枫,正在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')

# 启动Excel
os.system('start excel')

# 启动Word
os.system('start winword')

2、关闭应用程序

1
2
3
4
5
6
7
import os

# 关闭记事本
os.system('taskkill /F /IM notepad.exe')

# 关闭所有Excel
os.system('taskkill /F /IM excel.exe')

注意:Mac 用户用 killall 命令

3、检查程序是否运行

1
2
3
4
5
6
7
8
9
10
import psutil

# 检查Excel是否在运行
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') # Edge浏览器

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)

# 按Tab跳到下一个
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 编程实战课 帮你从零上手!