You are not logged in.

#1 2012-09-25 10:29:30

Mr. Alex
Registered: 2010-08-26
Posts: 623

[Solved][Python 3] How to center tkinter window?


I need to center window on the screen. The window that already has some contents like labels and buttons. Found this code snippet on Stack Overflow:

w = root.winfo_screenwidth()
h = root.winfo_screenheight()
rootsize = tuple(int(_) for _ in root.geometry().split('+')[0].split('x'))
x = w/2 - rootsize[0]/2
y = h/2 - rootsize[1]/2
root.geometry("%dx%d+%d+%d" % (rootsize + (x, y)))

but it doesn't work. It gives me centered window with no width or height when it has some size if I don't use this snippet. What is wrong in this code?

Last edited by Mr. Alex (2012-09-27 08:38:18)


#2 2012-09-26 13:54:20

Registered: 2012-09-02
Posts: 886

Re: [Solved][Python 3] How to center tkinter window?

I think it's normal for a fresh Tkinter window to report a width/height/position of 0 for some reason. It's only after the user moves and resizes the window that you will get the real values reported. So I have circumvented this problem by having a default width and height in the program which is used when info returns 0 for size. Set geometry to this default, then let the user resize and move and save the new values as the current defaults.


#3 2012-09-27 00:42:27

Registered: 2010-11-02
Posts: 63

Re: [Solved][Python 3] How to center tkinter window?

I think the main thing wrong with your code is you were asking for the window size before TK had decided what it should be. Your code works in the interactive interpreter if you run it line by line, but not if you run it all at once.

I adapted some code of my own for you:

from tkinter import Tk
from tkinter.ttk import Label
root = Tk()
Label(root, text="Hello world").pack()

# Apparently a common hack to get the window size. Temporarily hide the
# window to avoid update_idletasks() drawing the window in the wrong
# position.
root.update_idletasks()  # Update "requested size" from geometry manager

x = (root.winfo_screenwidth() - root.winfo_reqwidth()) / 2
y = (root.winfo_screenheight() - root.winfo_reqheight()) / 2
root.geometry("+%d+%d" % (x, y))

# This seems to draw the window frame immediately, so only call deiconify()
# after setting correct window position

I think it does what you want, although I have two screens side by side so the window is actually split between the two.


#4 2012-09-27 08:38:06

Mr. Alex
Registered: 2010-08-26
Posts: 623

Re: [Solved][Python 3] How to center tkinter window?

Thanks, this works.


Board footer

Powered by FluxBB