Get Screen Size – Width & Height using Tkinter

Introduction

Tkinter is a library in python which allows to create labels, buttons and many more elements .
tkinter is a graphical user interface. We will use tkinter library in python to get the screen size – width & height .

PROGRAM

Full program to get screen size(width and height):

import tkinter as tk

size=tk.Tk()
size.title("Screen Size")
size.geometry("800x600+275+115")
Width=size.winfo_screenwidth()
Height=size.winfo_screenheight()
heading=tk.Label(size, text="Screen size (Width & Height)")
w=tk.Label(size, text=f"Width: {Width}",font="arial 20 bold")
h=tk.Label(size, text=f"Height: {Height}",font="arial 20 bold")

heading.pack()
w.pack()
h.pack()

size.mainloop()

Program Explanation

Here is the program explanation which will help you understand the program easily :

Import the Tkinter library
import tkinter as tk

By importing tkinter as tk, we create an easy way for referring to Tkinter functions and objects. This keeps the code more concise.

Create the main window
size = tk.Tk()
size.title("Screen Size")

A new tkinter window is created and assigned to the variable size . Next we set the title as “Screen Size” which is seen in the top left corner in the window title bar.

Set window geometry
size.geometry("800x600+275+115")

The geometry() method sets the window’s size and initial position. The parameters inside the geometry method places the window at the specified location with a fixed size

Get screen Width and Height
Width = size.winfo_screenwidth()
Height = size.winfo_screenheight()

winfo_screenwidth() and winfo_screenheight() are methods that is used to retrieve  the width and height of the screen and they are stored in width and height variable.

Create label for Heading, Width & Height
heading = tk.Label(size, text="Screen size (Width & Height)")
w = tk.Label(size, text=f"Width: {Width}", font="arial 20 bold")
h = tk.Label(size, text=f"Height: {Height}", font="arial 20 bold")

A Label in Tkinter is used to display text. heading label displays the text “Screen size (Width & Height)” as the title for the window. w  label displays the width of the screen, retrieved from width. h  label displays the height of the screen, retrieved from height. both h and w are styled using font

Displaying the Labels
heading.pack()
w.pack()
h.pack()

The pack() method is used to arrange widgets in the window. Each label are displayed one after the other.

Running the main loop
size.mainloop()

The mainloop() method starts the Tkinter event loop, which waits for user actions such as clicks, keypresses etc. Without this loop, the GUI will not run and will close immediately after opening. It keeps the window active and responsive until you manually close it.

 

Output

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top