python tkinter界面居中显示的方法

作者:猪哥 2018-10-16

由于tkinter没有直接提供居中显示的api,因此,要想将tk的对话框居中显示,需要用到tk自带的设定位置的方法geometry()

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))

通过maxsize()方法获得显示器的分辨率,再通过winfo_reqwidth/height()方法获取当前对话框的大小。

这里需要注意的是,winfo_width和winfo_reqwidth的区别,前者是当前窗口大小,不一定是原定大小,如果此窗口还未开始mainloop,那么返回值会为0。因此,要在创建时居中显示,那么得用winfo_reqwidth,即取得窗口应该有的大小。

最后,用geometry()来设定窗口大小和显示的位置。

相关文章

精彩推荐