ericc
ericc

Reputation: 781

python tkinter hide the window during widget creation

I have a small annoying problem so I come to you to see if you can help to solve it. I have the following code in Python2.7:

# main window
root = tk.Tk()
root.title('My application')
# create the objects in the main window
w = buildWidgetClass(root)
# size of the screen (monitor resolution)
screenWi = root.winfo_screenwidth()
screenHe = root.winfo_screenheight()
# now that widgets are created, find the widht and the height
root.update()
guiWi = root.winfo_width()
guiHe = root.winfo_height()
# position of the window
x = screenWi / 2 - guiWi / 2
y = screenHe / 2 - guiHe / 2
root.geometry("%dx%d+%d+%d" % (guiWi, guiHe, x, y))

So I create the main window (without any size) I insert widgets inside, then I define the size of the result, and place it in the middle of the screen.

The number of widget in the window may vary, so the resulting size!

So far, so good, it works ! My only problem is that the window first appear in the left top corner of the screen, then repositioned to the center. Not a big deal, but not really professional neither.

So my idea was to hide the main window during the widgets creation time and then make it appearing after having defined the geometry.

So after the first line, I added :

root.withdraw()

then at the end :

root.update()
root.deiconify()

but when the window reappear, it wasn't re-sized by the widget and have a size of 1x1 !! I tried to replace root.withdraw() by root.iconify(), the window is correctly re-sized but, surprisingly, isn't deiconified at the end !!!

I'm a little bit lost on this ...

Upvotes: 0

Views: 2482

Answers (2)

ericc
ericc

Reputation: 781

Finally with the input of kalgasnik, I have a working code

# main window
root = tk.Tk()
# hide the main window during time we insert widgets
root.withdraw()

root.title('My application')
# create the objects in the main window with .grid()
w = buildWidgetClass(root)
# size of the screen (monitor resolution)
screenWi = root.winfo_screenwidth()
screenHe = root.winfo_screenheight()
# now that widgets are created, find the width and the height
root.update()
# retrieve the requested size which is different as the current size
guiWi = root.winfo_reqwidth()
guiHe = root.winfo_reqheight()
# position of the window
x = (screenWi - guiWi) / 2
y = (screenHe - guiHe) / 2
root.geometry("%dx%d+%d+%d" % (guiWi, guiHe, x, y))
# restore the window
root.deiconify()

Thanks a lot to both of you for your time and your help

Upvotes: 1

kalgasnik
kalgasnik

Reputation: 3205

Using root.winfo_reqwidth instead of root.winfo_width may help in your case.

Upvotes: 1

Related Questions