Python 中最大化窗口的分辨率

问题描述 投票:0回答:2

是否有内置函数直接的方式来获取Python中的最大化窗口分辨率(例如在没有任务栏的Windows全屏上)? 我已经尝试了其他帖子中的一些内容,其中存在一些主要的缺点

  1. c类型
import ctypes 
user32 = ctypes.windll.user32 
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)

简单,但是我得到了全屏的分辨率。

  1. tkinter
import tkinter as tk
root = tk.Tk()  # Create an instance of the class.
root.state('zoomed')  # Maximized the window.
root.update_idletasks()  # Update the display.
screensize = [root.winfo_width(), root.winfo_height()]
root.mainloop()

有效,但它并不是很直接,最重要的是,我不知道如何使用 root.destroy() 或 root.quit() 成功退出循环。手动关闭窗口当然不是一个选择。

  1. matplotlib
import matplotlib.pyplot as plt
plt.figure(1)
plt.switch_backend('QT5Agg')
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
print(plt.gcf().get_size_inches())
然后打印

[6.4 4.8]
,但是如果我单击创建的窗口,并再次执行
print(plt.gcf().get_size_inches())
,我会打印
[19.2  10.69]
,我发现这非常不一致! (正如您可以想象的那样,必须进行交互才能获得最终值绝对不是一个选择。)

python matplotlib tkinter ctypes resolution
2个回答
1
投票

根据[MS.Learn]:GetSystemMetrics函数(winuser.h)强调是我的):

SM_CXFULLSCREEN

16

主显示监视器上全屏窗口的客户区域宽度(以像素为单位)。要获取未被系统任务栏或应用程序桌面工具栏遮挡的屏幕部分的坐标,请使用 SPI_GETWORKAREA 值调用 SystemParametersInfo 函数。

SM_CY全屏同样如此。

示例:

>>> import ctypes as cts
>>>
>>>
>>> SM_CXSCREEN = 0
>>> SM_CYSCREEN = 1
>>> SM_CXFULLSCREEN = 16
>>> SM_CYFULLSCREEN = 17
>>>
>>> user32 = cts.windll.user32
>>> GetSystemMetrics = user32.GetSystemMetrics
>>>
>>> # @TODO - cfati: Don't forget about the 2 lines below !!!
>>> GetSystemMetrics.argtypes = (cts.c_int,)
>>> GetSystemMetrics.restype = cts.c_int
>>>
>>> GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)  # Entire (primary) screen
(1920, 1080)
>>> GetSystemMetrics(SM_CXFULLSCREEN), GetSystemMetrics(SM_CYFULLSCREEN)  # Full screen window
(1920, 1017)

关于代码中的@TODO:检查[SO]:通过ctypes从Python调用的C函数返回不正确的值(@CristiFati的答案),以了解使用CTypes(调用函数)时的常见陷阱。


1
投票

如果您不希望窗口持续存在,只需从 tkinter 代码中删除 mainloop 方法即可。

import tkinter as tk
root = tk.Tk()  # Create an instance of the class.
root.state('zoomed')  # Maximized the window.
root.update_idletasks()  # Update the display.
screensize = [root.winfo_width(), root.winfo_height()]

我还发现这可能会有所帮助,并且更多的是您正在寻找的内容;我使用的是Linux,所以无法测试。

from win32api import GetSystemMetrics

print("Width =", GetSystemMetrics(0))
print("Height =", GetSystemMetrics(1))

如何在 Python 中获取显示器分辨率?

© www.soinside.com 2019 - 2024. All rights reserved.