How can I tell a Tkinter window where to open, based on screen dimensions? I would like it to open in the middle.
Use the geometry() method to change the size and location of the window. Use the resizable() method to specify whether a window can be resizable horizontally or vertically. Use the window. attributes('-alpha',0.5) to set the transparency for the window.
In order to place a tkinter window at the center of the screen, we can use the PlaceWindow method in which we can pass the toplevel window as an argument and add it into the center. We can also set the window to its center programmatically by defining its geometry.
To set a specific size to the window when using Python tkinter, use geometry() function on the Tk() class variable. where width and height should be replaced with integers that represent the width and height of the window respectively.
According to the conventions, the root window in Tkinter is usually called "root", but you are free to call it by any other name. The third line executed the mainloop (that is, the event loop) method of the root object. The mainloop method is what keeps the root window visible.
This answer is based on Rachel's answer. Her code did not work originally, but with some tweaking I was able to fix the mistakes.
import tkinter as tk root = tk.Tk() # create a Tk root window w = 800 # width for the Tk root h = 650 # height for the Tk root # get screen width and height ws = root.winfo_screenwidth() # width of the screen hs = root.winfo_screenheight() # height of the screen # calculate x and y coordinates for the Tk root window x = (ws/2) - (w/2) y = (hs/2) - (h/2) # set the dimensions of the screen # and where it is placed root.geometry('%dx%d+%d+%d' % (w, h, x, y)) root.mainloop() # starts the mainloop
Try this
import tkinter as tk def center_window(width=300, height=200): # get screen width and height screen_width = root.winfo_screenwidth() screen_height = root.winfo_screenheight() # calculate position x and y coordinates x = (screen_width/2) - (width/2) y = (screen_height/2) - (height/2) root.geometry('%dx%d+%d+%d' % (width, height, x, y)) root = tk.Tk() center_window(500, 400) root.mainloop()
Source
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With