如何在Tkinter中将窗口居中放置在屏幕上?


问题内容

我试图居中tkinter窗口。我知道我可以以编程方式获取窗口的大小和屏幕的大小,并使用它来设置几何形状,但是我想知道是否有更简单的方法将窗口居中放置在屏幕上。


问题答案:

你可以尝试使用方法winfo_screenwidthwinfo_screenheight,你的分别返回的宽度和高度(以像素为单位)Tk实例(窗口),并与一些基本的数学可以居中你的窗口:

import tkinter as tk
from PyQt4 import QtGui    # or PySide

def center(toplevel):
    toplevel.update_idletasks()

    # Tkinter way to find the screen resolution
    # screen_width = toplevel.winfo_screenwidth()
    # screen_height = toplevel.winfo_screenheight()

    # PyQt way to find the screen resolution
    app = QtGui.QApplication([])
    screen_width = app.desktop().screenGeometry().width()
    screen_height = app.desktop().screenGeometry().height()

    size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
    x = screen_width/2 - size[0]/2
    y = screen_height/2 - size[1]/2

    toplevel.geometry("+%d+%d" % (x, y))
    toplevel.title("Centered!")

if __name__ == '__main__':
    root = tk.Tk()
    root.title("Not centered")

    win = tk.Toplevel(root)
    center(win)

    root.mainloop()

update_idletasks在检索窗口的宽度和高度之前先调用method,以确保返回的值是准确的。

Tkinter 看不到是否有2个或更多水平或垂直扩展的监视器。因此,您将获得所有屏幕的总分辨率,并且窗口将最终显示在屏幕中间的某个位置。

__另一方面, PyQt
也看不到多显示器环境,但是它将仅获得左上显示器的分辨率(想象一下4个显示器,2个向上和2个向下制作一个正方形)。因此,它通过将窗口置于该屏幕的中心来完成工作。如果您不想同时使用
PyQtTkinter ,则最好从一开始就使用PyQt。