How to Get Screen Resolution in Python Easily
You can get screen resolution in Python using the
tkinter library by creating a root window and calling root.winfo_screenwidth() and root.winfo_screenheight(). Alternatively, the pyautogui library provides pyautogui.size() to return screen width and height.Syntax
Using tkinter, you create a root window and call methods to get width and height.
Using pyautogui, you call size() to get a tuple with width and height.
python
import tkinter as tk root = tk.Tk() width = root.winfo_screenwidth() height = root.winfo_screenheight() root.destroy() # Using pyautogui import pyautogui screen_size = pyautogui.size() # returns Size(width, height)
Example
This example shows how to get and print the screen resolution using both tkinter and pyautogui.
python
import tkinter as tk import pyautogui # Using tkinter root = tk.Tk() width = root.winfo_screenwidth() height = root.winfo_screenheight() root.destroy() print(f"Screen resolution using tkinter: {width}x{height}") # Using pyautogui screen_size = pyautogui.size() print(f"Screen resolution using pyautogui: {screen_size.width}x{screen_size.height}")
Output
Screen resolution using tkinter: 1920x1080
Screen resolution using pyautogui: 1920x1080
Common Pitfalls
- Not calling
root.destroy()after usingtkintercan leave a blank window open. - For
pyautogui, the library must be installed first usingpip install pyautogui. - Running these on headless servers or environments without a display will fail.
python
import tkinter as tk # Wrong: forgetting to destroy the root window root = tk.Tk() width = root.winfo_screenwidth() height = root.winfo_screenheight() print(f"Width: {width}, Height: {height}") # The window stays open and blocks the program # Right way: root.destroy()
Quick Reference
Summary of methods to get screen resolution in Python:
| Method | Description | Requires Installation |
|---|---|---|
| tkinter | Built-in Python library; use winfo_screenwidth() and winfo_screenheight() | No |
| pyautogui | Third-party library; use size() to get width and height | Yes, install with pip install pyautogui |
Key Takeaways
Use tkinter's winfo_screenwidth() and winfo_screenheight() to get screen size without extra installs.
pyautogui.size() returns screen resolution as a tuple but requires installing the library.
Always call root.destroy() after tkinter to close the hidden window.
These methods work only on systems with a graphical display.
Check your environment if you get errors related to display or GUI.