如何在 Tkinter 的屏幕上居中显示窗口? [英] How to center a window on the screen in Tkinter?

查看:55
本文介绍了如何在 Tkinter 的屏幕上居中显示窗口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to center a tkinter window. I know I can programatically get the size of the window and the size of the screen and use that to set the geometry, but I'm wondering if there's a simpler way to center the window on the screen.

推荐答案

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

You can try to use the methods winfo_screenwidth and winfo_screenheight, which return respectively the width and height (in pixels) of your Tk instance (window), and with some basic math you can center your window:

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 方法,以确保返回的值是准确的.

I am calling update_idletasks method before retrieving the width and the height of the window in order to ensure that the values returned are accurate.

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

Tkinter doesn't see if there are 2 or more monitors extended horizontal or vertical. So, you 'll get the total resolution of all screens together and your window will end-up somewhere in the middle of the screens.

PyQt 另一方面,也没有看到多显示器环境,但它只会获得左上角显示器的分辨率(想象一下 4 个显示器,2 个向上和 2 个向下一个正方形).因此,它通过将窗口放在该屏幕的中心来完成工作.如果您不想同时使用 PyQtTkinter,也许从一开始就使用 PyQt 会更好.

PyQt from the other hand, doesn't see multi-monitors environment either, but it will get only the resolution of the Top-Left monitor (Imagine 4 monitors, 2 up and 2 down making a square). So, it does the work by putting the window on center of that screen. If you don't want to use both, PyQt and Tkinter, maybe it would be better to go with PyQt from start.

这篇关于如何在 Tkinter 的屏幕上居中显示窗口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆