tkinter winfo_screenwidth() 与双显示器一起使用时

Kar*_*pov 7 python tkinter tkinter-canvas

使用 tkinter 画布,为了计算我显示的图形的大小,我通常使用函数winfo_screenwidth(),并相应地调整我的对象的大小。但是当在有两个显示器的系统上使用时,winfo_screenwidth()返回两个显示器的组合宽度——这会弄乱我的图形。如何分别找出每台显示器的屏幕宽度(以像素为单位)?

我在各种 Linux 机器(Ubuntu 和 Mint)上使用多个版本的 Python 3.x 和多个版本的 tkinter(均为 8.5 或更高版本)时遇到了这个问题。

例如,第一台显示器的宽度为 1440 像素。第二个是 1980 像素宽。winfo_screenwidth()返回 3360。

我需要找到一种方法来独立确定每个显示器的屏幕宽度。

谢谢!

小智 8

这是一个老问题,但仍然是:对于跨平台解决方案,您可以尝试screeninfo模块,并通过以下方式获取有关每个显示器的信息:

import screeninfo
screeninfo.get_monitors()
Run Code Online (Sandbox Code Playgroud)

如果您需要知道您的窗口之一位于哪台显示器上,您可以使用:

def get_monitor_from_coord(x, y):
    monitors = screeninfo.get_monitors()

    for m in reversed(monitors):
        if m.x <= x <= m.width + m.x and m.y <= y <= m.height + m.y:
            return m
    return monitors[0]

# Get the screen which contains top
current_screen = get_monitor_from_coord(top.winfo_x(), top.winfo_y())

# Get the monitor's size
print current_screen.width, current_screen.height
Run Code Online (Sandbox Code Playgroud)

(其中 top 是你的 Tk 根)


Iro*_*k20 2

基于这个略有不同的问题,我建议如下:

 t.state('zoomed')
 m_1_height= t.winfo_height()
 m_1_width= t.winfo_width() #this is the width you need for monitor 1 
Run Code Online (Sandbox Code Playgroud)

这样窗口就会缩放以填满一个屏幕。另一台显示器的宽度正好wininfo_screenwidth()-m_1_width

我还想向您指出这里找到的用于查找窗口显示器尺寸的出色 ctypes 方法。注意:与帖子所说的不同,ctypes 在 stdlib 中!无需安装任何东西。