tkinter windows which is 250 pixel wide and 50 pixel height appear at the center of the screen in python

Here's the code to create a tkinter window that appears at the center of the screen with a width of 250 pixels and height of 50 pixels:

main.py
from tkinter import Tk

# create window
root = Tk()

# set window width and height
window_width = 250
window_height = 50

# get screen width and height
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()

# calculate x and y coordinates for the window to be centered
x = int((screen_width/2) - (window_width/2))
y = int((screen_height/2) - (window_height/2))

# set the dimensions of the screen 
# and where it is placed 
root.geometry("{}x{}+{}+{}".format(window_width, window_height, x, y))

# run the main loop
root.mainloop()
560 chars
24 lines

In the above code, we first import the Tk class from tkinter. Then we create an instance of the Tk class and store it in the root variable.

After that, we set the width and height of the window to 250 and 50 pixels respectively.

We then get the width and height of the screen using winfo_screenwidth() and winfo_screenheight() methods of the root window.

We calculate the x and y coordinates of the window such that it appears centered on the screen by subtracting the window width and height from the screen width and height, respectively.

Finally, we set the geometry of the window using the geometry() method, passing it the window width, height, x-coordinate and y-coordinate as arguments.

We then start the event loop using the mainloop() method. This creates the window and displays it at the center of the screen.

gistlibby LogSnag