SoFunction
Updated on 2024-12-13

python tkinter interface centered display method

Since tkinter doesn't directly provide an api for centered display, to center tk's dialogs, you need to use tk's own position-setting method, geometry().

nScreenWid, nScreenHei = ()
nCurWid = tkLogin.winfo_reqwidth()
nCurHeight = tkLogin.winfo_reqheight()
("{}x{}+{}+{}".format(nCurWid, nCurHeight, nScreenWid/2 - nCurWid/2, nScreenHei/2 - nCurHeight/2))

Get the resolution of the monitor by maxsize() method, then get the size of the current dialog by winfo_reqwidth/height() method.

It should be noted that the difference between winfo_width and winfo_reqwidth is that the former is the current window size, not necessarily the original size, and if the window has not yet begun the mainloop, then the return value will be 0. Therefore, in order to center the display at the time of creation, then you have to use winfo_reqwidth, that is, to obtain the size of the window that should be there.

Finally, geometry() is used to set the window size and the position of the display.

The above method of centering the display of this python tkinter interface is all that I have shared with you.