杰瑞科技汇

python windowcontrol

Of course! "Window Control" in Python can mean several things, from controlling your own application's window to automating and managing other applications' windows.

python windowcontrol-图1
(图片来源网络,侵删)

I'll cover the most common and powerful methods, categorized by use case.

Controlling Your Own GUI Application's Window

This is the most straightforward use case. You're building a GUI (Tkinter, PyQt, etc.) and want to control its behavior: minimize, maximize, close, set its position, etc.

For Tkinter

Tkinter is Python's built-in GUI library. It has simple and direct methods for window control.

import tkinter as tk
import time
def minimize_window():
    """Minimizes the main window."""
    root.iconify() # This is the method to minimize
def maximize_window():
    """Maximizes the main window."""
    root.state('zoomed') # For Windows. For macOS, use 'zoomed'
def restore_window():
    """Restores the window to its normal size."""
    root.state('normal')
def move_window():
    """Moves the window to a new position."""
    # The geometry string is: "widthxheight+x_offset+y_offset"
    root.geometry("400x300+500+200") # 500px from left, 200px from top
def close_window():
    """Closes the application window."""
    root.destroy()
# --- Create the main window ---
root = tk.Tk()"Tkinter Window Control")
root.geometry("600x400+100+100") # Initial size and position
# --- Create buttons to trigger actions ---
btn_minimize = tk.Button(root, text="Minimize", command=minimize_window)
btn_minimize.pack(pady=5)
btn_maximize = tk.Button(root, text="Maximize", command=maximize_window)
btn_maximize.pack(pady=5)
btn_restore = tk.Button(root, text="Restore", command=restore_window)
btn_restore.pack(pady=5)
btn_move = tk.Button(root, text="Move Window", command=move_window)
btn_move.pack(pady=5)
btn_close = tk.Button(root, text="Close Window", command=close_window, bg="red", fg="white")
btn_close.pack(pady=5)
root.mainloop()

Key Tkinter Methods:

python windowcontrol-图2
(图片来源网络,侵删)
  • root.iconify(): Minimizes the window.
  • root.state('zoomed'): Maximizes the window (Windows).
  • root.state('normal'): Restores the window.
  • root.geometry("WxH+X+Y"): Sets the size (Width x Height) and position (X offset from left, Y offset from top).
  • root.attributes('-topmost', True): Brings the window to the front and keeps it there.
  • root.attributes('-alpha', 0.5): Makes the window semi-transparent (0.0 to 1.0).

For PyQt / PySide

PyQt and PySide are more feature-rich toolkits. They use a QMainWindow as the central widget.

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget
class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt Window Control")
        self.setGeometry(100, 100, 600, 400) # x, y, width, height
        # Create a central widget and layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        # --- Create buttons ---
        btn_minimize = QPushButton("Minimize")
        btn_minimize.clicked.connect(self.showMinimized)
        btn_maximize = QPushButton("Maximize")
        btn_maximize.clicked.connect(self.showMaximized)
        btn_restore = QPushButton("Restore")
        btn_restore.clicked.connect(self.showNormal)
        btn_close = QPushButton("Close")
        btn_close.clicked.connect(self.close)
        layout.addWidget(btn_minimize)
        layout.addWidget(btn_maximize)
        layout.addWidget(btn_restore)
        layout.addWidget(btn_close)
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

Key QMainWindow Methods:

  • self.showMinimized(): Minimizes the window.
  • self.showMaximized(): Maximizes the window.
  • self.showNormal(): Restores the window.
  • self.close(): Closes the window.
  • self.setGeometry(x, y, width, height): Sets size and position.
  • self.move(x, y): Only sets position.
  • self.resize(width, height): Only sets size.

Automating and Controlling External Windows (GUI Automation)

This is a more advanced and powerful technique, often used for testing, automation, or scripting interactions with other applications (like a web browser, a game, or a legacy desktop app).

The best library for this is pygetwindow. It's a simple, cross-platform wrapper around more complex underlying libraries (pywin32 on Windows, AppKit on macOS, wnck on Linux).

python windowcontrol-图3
(图片来源网络,侵删)

Installation

pip install pygetwindow

Example: Controlling Notepad or Another App

Let's say you have Notepad open. You can control it from your Python script.

import pygetwindow as gw
import time
# --- Find the window you want to control ---
# You can use the window's title.
# To see all open window titles, run: gw.getAllTitles()
try:
    notepad_window = gw.getWindowsWithTitle('Notepad')[0]
    print(f"Found window: '{notepad_window.title}'")
except IndexError:
    print("Notepad window not found. Please open Notepad and run again.")
    exit()
# --- Control the window ---
# 1. Maximize the window
print("Maximizing window...")
notepad_window.maximize()
time.sleep(1)
# 2. Minimize the window
print("Minimizing window...")
notepad_window.minimize()
time.sleep(1)
# 3. Restore (un-minimize/maximize) the window
print("Restoring window...")
notepad_window.restore()
time.sleep(1)
# 4. Resize and Move the window
print("Resizing and moving window...")
notepad_window.resizeTo(600, 400)
notepad_window.moveTo(800, 300)
time.sleep(1)
# 5. Activate the window (bring it to the foreground)
print("Activating window...")
notepad_window.activate()
# 6. Close the window
# print("Closing window...")
# notepad_window.close() # Be careful with this!
print("Script finished.")

Key pygetwindow Methods:

  • gw.getWindowsWithTitle('title'): Returns a list of window objects matching the title. [0] gets the first one.
  • gw.getActiveWindow(): Gets the currently active/focused window.
  • window.activate(): Brings the window to the foreground and gives it focus.
  • window.maximize(), window.minimize(), window.restore(): Standard window states.
  • window.resizeTo(width, height): Sets the window's size.
  • window.moveTo(x, y): Sets the window's position.
  • window.close(): Closes the window.
  • window.size: A tuple (width, height) of the current size.
  • window.left, window.top: The current x and y coordinates of the top-left corner.

Advanced: Low-Level Window Hooking (For Games & Complex Apps)

For applications that actively resist being controlled (like many games or apps with custom rendering), pygetwindow might not be enough. You need a lower-level approach.

The pywin32 library on Windows gives you direct access to the Windows API.

Installation (Windows only)

pip install pywin32

Example: Getting a Window's Handle (HWND) and Title

This example shows how to find a window by its class name (like "Notepad" or "Chrome_WidgetWin_1") and get its handle, which is the unique ID for the window in the Windows OS.

import win32gui
import time
def find_window_by_class(class_name, window_title=None):
    """Finds a window by its class name and optional title."""
    hwnd = win32gui.FindWindow(class_name, window_title)
    if hwnd:
        print(f"Found window handle (HWND): {hwnd}")
        return hwnd
    else:
        print(f"Window with class '{class_name}' not found.")
        return None
# --- Find Notepad using its class name ---
# You can find class names using tools like AutoIt's "Window Info" tool or Spy++.
notepad_class = "Notepad"
notepad_hwnd = find_window_by_class(notepad_class)
if notepad_hwnd:
    # You can now use this HWND with other win32gui functions= win32gui.GetWindowText(notepad_hwnd)
    print(f"Window Title is: '{title}'")
    # To control it, you'd send messages directly to the window
    # For example, to close it:
    # win32gui.PostMessage(notepad_hwnd, win32con.WM
分享:
扫描分享到社交APP
上一篇
下一篇