INTRODUCTION
This Python script demonstrates how to use the Tkinter library to access screen dimensions in a graphical user interface (GUI) environment. Tkinter, a built-in toolkit in Python, allows developers to create windowed applications effortlessly. In this example, we initialize a root window (which is not displayed), then utilize the methods winfo_screenwidth()
and winfo_screenheight()
to retrieve the width and height of the user’s screen in pixels. The script prints these values to the console, providing useful information about the display. Finally, the root window is destroyed to clean up resources and ensure the program exits smoothly.
CODE:
import tkinter as tk
# Create a Tkinter root window
root = tk.Tk()
# Get the width and height of the screen
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
# Print the screen dimensions
print(f”Screen width: {screen_width}, Screen height: {screen_height}”)
# Destroy the root window
root.destroy()
EXPLANATION
This Python script demonstrates how to use the Tkinter library to retrieve and display the dimensions of the user’s screen. Below is a detailed breakdown of each component of the code:
- Importing the Tkinter Library:
The script begins by importing the Tkinter library, which is essential for creating graphical user interfaces in Python. The alias
tk
is used for convenience. - Creating a Root Window:
A root window is instantiated using the
Tk()
class. This root window serves as the main window for any Tkinter application. Although we won’t display this window, it is necessary for accessing various Tkinter functionalities. - Retrieving Screen Dimensions:
winfo_screenwidth()
: This method retrieves the width of the screen in pixels.winfo_screenheight()
: This method retrieves the height of the screen in pixels.
These methods provide the necessary information about the user’s display, which can be particularly useful for applications that need to adapt their layout based on screen size.
- Printing the Screen Dimensions:
The script formats the retrieved screen dimensions into a string and prints them to the console. This output gives users immediate feedback regarding their display size.
- Destroying the Root Window:
The final line of the script calls the
destroy()
method on the root window. This step is crucial for releasing resources and ensuring that the application exits cleanly without leaving any lingering processes running.
OUTPUT :Screen width: 1536, Screen height: 864
CONCLUSION: