[파이썬] pyautogui 화면 해상도 조절

In this blog post, we will explore how to adjust the screen resolution using pyautogui library in Python. PyAutoGUI is a cross-platform Python library that allows automation of mouse movements, keyboard inputs, and screen interactions.

Adjusting the screen resolution can be useful in scenarios where you need to run automated tests or perform tasks that require specific screen resolutions. By changing the screen resolution programmatically, you can simulate different display settings and ensure that your application or scripts behave correctly.

Prerequisites

Before proceeding, make sure you have pyautogui installed on your system. You can install it using pip:

pip install pyautogui

Also, ensure that you have admin or root access to your system as changing screen resolution requires administrative privileges.

Steps to adjust screen resolution

  1. Import the pyautogui module in your Python script:
import pyautogui
  1. Get the current screen resolution using the pyautogui.size() function:
screen_width, screen_height = pyautogui.size()
  1. Set the new desired screen resolution values. Make sure the values are within the supported range of your monitor:
new_width = 1920
new_height = 1080
  1. Use the pyautogui.moveTo() function to move the mouse to the desired position on the screen. This step is necessary because changing screen resolution triggers an alert window that needs to be interacted with. By moving the mouse to a specific position, we can ensure that the alert window is in focus:
pyautogui.moveTo(0, 0)
  1. Use the pyautogui.hotkey() function to press the keyboard shortcut for opening the display settings:
pyautogui.hotkey('win', 'p')
  1. Use the pyautogui.typewrite() function to simulate typing the desired resolution values:
pyautogui.typewrite(f"{new_width}x{new_height}")
  1. Use the pyautogui.press() function to press the Enter key to apply the new screen resolution:
pyautogui.press('enter')

Conclusion

In this blog post, we learned how to adjust the screen resolution using pyautogui in Python. By following the above steps, you can programatically change the screen resolution for various purposes. Keep in mind that changing the screen resolution can affect the visual layout of your applications or scripts, so make sure to handle such changes appropriately.

Remember to handle any exceptions that may arise and include necessary error handling in your code. With pyautogui, you have the power to automate and control screen interactions with ease.

Happy coding!