[파이썬] pyautogui 윈도우 창 크기 및 위치 조절

PyAutoGUI Logo

Introduction

In this blog post, we will discuss how to use pyautogui library in Python to resize and move windows on Windows operating system. This can be useful when automating tasks that require specific window sizes or positions. PyAutoGUI is a cross-platform GUI automation library that allows you to control the mouse, keyboard, and other GUI automation tasks.

Installing PyAutoGUI

Before we get started, we need to make sure we have pyautogui installed. To install it, open your command prompt or terminal and run the following command:

pip install pyautogui

Once installed, you can import it into your Python script using the following line of code:

import pyautogui

Resizing a Window

To resize a window using pyautogui, we can make use of the pyautogui.moveTo() and pyautogui.dragTo() functions. The moveTo() function moves the mouse cursor to a specific location on the screen, and dragTo() function simulates dragging the mouse cursor from one point to another.

First, we need to determine the current position and size of the window. We can use the pyautogui.position() function to get the current mouse coordinates. We can then move the mouse to one corner of the window and simulate dragging it to resize the window.

# Get current mouse position
current_x, current_y = pyautogui.position()

# Move the mouse to a corner of the window
pyautogui.moveTo(current_x, current_y)

# Simulate dragging the mouse to resize the window
pyautogui.dragTo(new_x, new_y, duration=1)

Replace new_x and new_y with the desired coordinates of the new window size. The duration parameter specifies how long the dragging animation should take.

Moving a Window

To move a window using pyautogui, we can make use of the pyautogui.dragTo() function. We need to determine the current position of the window and the desired position where we want to move the window. We can then simulate dragging the mouse cursor from the current position to the desired position.

# Get current mouse position
current_x, current_y = pyautogui.position()

# Calculate the desired position
new_x = current_x + 100
new_y = current_y + 100

# Simulate dragging the mouse to move the window
pyautogui.dragTo(new_x, new_y, duration=1)

Replace new_x and new_y with the desired coordinates of the new window position. The duration parameter specifies how long the dragging animation should take.

Conclusion

With the help of pyautogui, we can easily resize and move windows programmatically in Python. This can be useful for automating repetitive tasks or creating scripts that require specific window sizes or positions. Make sure to experiment and adjust the code to suit your needs. Happy coding!

References: