You are not logged in.
Hi.
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)
Offline
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.
Offline
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.withdraw()
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
root.deiconify()
I think it does what you want, although I have two screens side by side so the window is actually split between the two.
Offline
Thanks, this works.
Offline