python tkinter interface center display method

  • 2020-12-09 00:57:18
  • OfStack

Since tkinter does not provide api to be centered directly, to center the tk dialog, you need geometry(), the locale-setting method that tk comes with


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

The resolution of the display is obtained through the maxsize() method, and the size of the current dialog is obtained through the 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, while the former is the original size. If the window has not started mainloop, the return value will be 0. Therefore, to center the display at creation time, use winfo_reqwidth to get the size of the window as it should be.

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


Related articles: