pythongui监控window窗体
效果:
PIL实现
import tkinter as tk
from PIL import ImageTk
import pygetwindow as gw
import pyautogui
# Define the window title
window_title = "Plants vs. Zombies"
# Function to update the image in the tkinter window
def update_image():
if windows:
# Get the first matching window
window = windows[0]
# Get the window's coordinates and size
left, top, width, height = window.left, window.top, window.width, window.height
# Capture the window's content
screenshot = pyautogui.screenshot(region=(left, top, width, height))
# Convert to ImageTk
img_tk = ImageTk.PhotoImage(screenshot)
# Update the label with the new image
label.config(image=img_tk)
label.image = img_tk
# Call this function again after 1 second (1000 milliseconds)
root.after(1000, update_image)
else:
print(f"No window found with the title '{window_title}'")
# Create the tkinter root window
root = tk.Tk()
root.title("Real-time Window Capture")
# Create a label to hold the image
label = tk.Label(root)
label.pack()
# Find the window with the specified title
windows = gw.getWindowsWithTitle(window_title)
# Start updating the image
update_image()
# Run the tkinter main loop
root.mainloop()
MSS实现
import cv2 as cv
import numpy as np
import pygetwindow as gw
import mss
# Define the window title
window_title = "Plants vs. Zombies"
def get_window_rect(title):
windows = gw.getWindowsWithTitle(title)
if not windows:
raise ValueError(f"Window with title '{title}' not found.")
return windows[0]._rect
def capture_screen(rect):
with mss.mss() as sct:
monitor = {"left": rect.left, "top": rect.top, "width": rect.width, "height": rect.height}
img = sct.grab(monitor)
img_np = np.array(img)
img_np = cv.cvtColor(img_np, cv.COLOR_BGRA2BGR) # Convert BGRA to BGR
return img_np
def main():
try:
rect = get_window_rect(window_title)
print("Monitoring Window Rect:", rect)
while True:
img = capture_screen(rect)
cv.imshow("Plants vs. Zombies", img)
# Exit loop on 'q' key press
if cv.waitKey(1) == ord('q'):
break
except Exception as e:
print(f"Error: {e}")
cv.destroyAllWindows()
if __name__ == "__main__":
main()