我不是 WATSUP 用户,但我使用 pywinauto 做了一些非常相似的事情——在我的情况下,我正在运行许多自动化测试,这些测试以类似的方式打开各种 3rd 方程序,引发不方便的警告对话框。处理您不知道的对话框有点困难,但是如果您确实知道出现了哪些对话框,但不知道它们何时出现,您可以启动一个线程来处理这些弹出窗口。以下是我正在做的一个简单示例,它使用 pywinauto,但您可以将方法调整为 WATSUP:
import time
import threading
class ClearPopupThread(threading.Thread):
def __init__(self, window_name, button_name, quit_event):
threading.Thread.__init__(self)
self.quit_event = quit_event
self.window_name = window_name
self.button_name = button_name
def run(self):
from pywinauto import application, findwindows
while True:
try:
handles = findwindows.find_windows(title=self.window_name)
except findwindows.WindowNotFoundError:
pass #Just do nothing if the pop-up dialog was not found
else: #The window was found, so click the button
for hwnd in handles:
app = application.Application()
app.Connect(handle=hwnd)
popup = app[self.window_name]
button = getattr(popup, self.button_name)
button.Click()
if self.quit_event.is_set():
break
time.sleep(1) #should help reduce cpu load a little for this thread
本质上,这个线程只是一个无限循环,它按名称查找弹出窗口,如果找到,它会单击一个按钮来关闭窗口。如果您有许多弹出窗口,您可以在每个弹出窗口中打开一个线程(不过,这个错误并不过分高效)。因为它是一个无限循环,所以我让线程查看是否设置了事件,以允许我从主程序中停止线程。所以,在主程序中我做了这样的事情:
#Start the thread
quit_event = threading.Event()
mythread = ClearPopupThread('Window Popup Title', 'Yes button', quit_event)
# ...
# My program does it's thing here
# ...
# When my program is done I need to end the thread
quit_event.set()
这不一定是解决您的问题的唯一方法,但对我来说是一种有效的方法。抱歉,我在处理 WATSUP 方面帮不上什么忙(我总是发现 pywinauto 更容易使用),但我在 WATSUP 主页(http://www.tizmoi.net/watsup/intro.html)上注意到了,示例 2 在不使用线程的情况下执行了类似的操作,即查找命名窗口并单击该窗口上的特定按钮。