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

查看:430
本文介绍了如何在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_screenwidth winfo_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个向下制作一个正方形)。因此,它通过将窗口置于该屏幕的中心来完成工作。如果您不想同时使用 PyQt Tkinter ,则最好从一开始就使用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天全站免登陆