How to center a window on the screen in Tkinter?
You can try to use the methods winfo_screenwidth
and winfo_screenheight
, which return respectively the width and height (in pixels) of your Tk
instance (window), and with some basic math you can center your window:
import tkinter as tk
from PyQt4 import QtGui # or PySide
def center(toplevel):
toplevel.update_idletasks()
# Tkinter way to find the screen resolution
# screen_width = toplevel.winfo_screenwidth()
# screen_height = toplevel.winfo_screenheight()
# PyQt way to find the screen resolution
app = QtGui.QApplication([])
screen_width = app.desktop().screenGeometry().width()
screen_height = app.desktop().screenGeometry().height()
size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
x = screen_width/2 - size[0]/2
y = screen_height/2 - size[1]/2
toplevel.geometry("+%d+%d" % (x, y))
toplevel.title("Centered!")
if __name__ == '__main__':
root = tk.Tk()
root.title("Not centered")
win = tk.Toplevel(root)
center(win)
root.mainloop()
I am calling update_idletasks
method before retrieving the width and the height of the window in order to ensure that the values returned are accurate.
Tkinter doesn't see if there are 2 or more monitors extended horizontal or vertical. So, you 'll get the total resolution of all screens together and your window will end-up somewhere in the middle of the screens.
PyQt from the other hand, doesn't see multi-monitors environment either, but it will get only the resolution of the Top-Left monitor (Imagine 4 monitors, 2 up and 2 down making a square). So, it does the work by putting the window on center of that screen. If you don't want to use both, PyQt and Tkinter, maybe it would be better to go with PyQt from start.
Tkinter window center of screen
Add update_idletasks()
:
def centrar_ventana(self):
self.root.update_idletasks() #Add this line
width = self.login_window.winfo_width()
height = self.login_window.winfo_height()
x = (self.login_window.winfo_screenwidth() // 2) - (width // 2)
y = (self.login_window.winfo_screenheight() // 2) - (height // 2)
self.login_window.geometry('{}x{}+{}+{}'.format(width, height, x, y))
This updates the window so tkinter realises that it has changed size. This means it returns the correct sizes so the window is centered properly.
Centering window python tkinter
Ok I have found and fixed the problem. Piggybacking off of OregonTrail's solution, i found that if the window is the right size and you just want to change the location, then you can easily instead of setting the root's size, you can just move the window to the center.
w = root.winfo_reqwidth()
h = root.winfo_reqheight()
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('+%d+%d' % (x, y)) ## this part allows you to only change the location
I think that this answer isn't exactly in the center, probably off by a little since h was returning 200 when it should be less, but it looks to be at the center and works fine.
How to set python window center position
Does this center your window?
from tkinter import *
from tkinter import messagebox
from subprocess import call
root = Tk()
root.title("Main")
window_width,window_height = 500,500
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
position_top = int(screen_height/2 - window_height/2)
position_right = int(screen_width / 2 - window_width/2)
root.geometry(f'{window_width}x{window_height}+{position_right}+{position_top}')
def Ok():
pass
Label(root, text="Welcome").place(x=10, y=10)
Button(root, text="Add Student", command=Ok ,height = 3, width = 13).place(x=10, y=100)
root.mainloop()
Tkinter centering ctktoplevel window in middle of main window
from tkinter import Toplevel, Button, Tk
root = Tk()
width = 960
height = 540
root.geometry("%dx%d" % (width, height))
def new_window() :
win = Toplevel()
win.geometry("%dx%d+%d+%d" % (480, 270, root.winfo_x() + width/4, root.winfo_y() + height/4))
#the geometry method can take four numbers as a string argument
#first two numbers for dimensions
#second two numbers for the position of the opened window
#the position is always the top left of your window
#winfo_x and winfo_y are two methods
#they determine the current position of your window
Button(root, text = "open", command = new_window).pack()
root.mainloop()
You can test the code and make it satisfy your needs.
I hope that helps !
Centering a Tkinter Toplevel window in both windows and remote X11?
Solved! Had to tweak the order of the calls a little bit:
#// Done!
self.withdraw()
self.grid()
self.transient(self._parent)
self.grab_set()
self.form.initial_focus()
center(self)
self.deiconify()
self._parent._parent.wait_window(self)
But the real fix was in the center()
function I lifted from this answer, by changing the calls to winfo_width()
/winfo_height()
to winfo_reqwidth()
/winfo_reqheight()
and adding a call to update()
as the first call in center()
. Now I get my dialog windows to pop up in the center without seeing them move, focus is applied correctly, and it works on both Windows and remote X11. Maybe one day, I'll find out how well it works on Mac OS X/Aqua.
How to center two frames in one window using tkinter?
You have to tell widgets to expand if the grid resizes. You can do that with columnconfigure
. Using the sticky
parameter you can tell the widget how to react. Have a look at Handling Resize at this site: https://tkdocs.com/tutorial/grid.html
import tkinter as tk
root = tk.Tk()
frame1 = tk.Frame(root, bg='gold')
frame1.pack(fill=tk.X)
frame1.columnconfigure(0, weight=1)
frame2 = tk.Frame(root)
frame2.pack()
frame1label1 = tk.Label(frame1, bg='gold', text='Top label')
frame1label1.grid(row=0, column=0)
frame2label = tk.Label(frame2, text='Bottom label')
frame2label.pack()
root.mainloop()
Related Topics
How to Cleanly Uninstall Ansible
How to Remove a Pandas Dataframe from Another Dataframe
How to Block Comment Code in the Ipython Notebook
Python: How to Calculate the Sum of Numbers from a File
Pip3: Command Not Found But Python3-Pip Is Already Installed
Merge Multiple Rows to Single Row - Pandas
Sharing a Complex Object Between Processes
How to Set Proxy for Chrome in Python Webdriver
How to Get Value from Json List Within Robot Framework
How to Change the Title Bar in Tkinter
How to Update Sqlalchemy Orm Object by a Python Dict
Plot Two Histograms on Single Chart With Matplotlib
Python3 Tkinter Set Image Size
How to Find Consecutive Numbers in a Python List
How to Delete Lines from CSV File Using Python
Import Local Module in Jupyter Notebook
Algorithm for Distributing a Number Between Certain Number of Chunks