Python 中最大化 window 的分辨率

Resolution of a maximized window in Python

是否有内置函数直接方法来获得分辨率最大化 window in Python(例如 Windows 全屏没有任务栏) ? 我尝试了其他帖子中的一些东西,这些东西提出了一些主要的缺点:

  1. ctypes
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() 成功退出循环。手动关闭 window 当然不是一个选项。

  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],但是如果我单击创建的 window,然后再次执行 print(plt.gcf().get_size_inches()),我会打印 [19.2 10.69],我发现这非常不一致! (正如您所想象的,必须进行交互才能获得最终价值绝对不是一种选择。)

根据[MS.Docs]: GetSystemMetrics function强调是我的):

SM_CXFULLSCREEN

16

The width of the client area for a full-screen window on the primary display monitor, in pixels. To get the coordinates of the portion of the screen that is not obscured by the system taskbar or by application desktop toolbars, call the SystemParametersInfo function with the SPI_GETWORKAREA value.

SM_CYFULLSCREEN.

也一样

示例:

>>> import ctypes as ct
>>>
>>>
>>> SM_CXSCREEN = 0
>>> SM_CYSCREEN = 1
>>> SM_CXFULLSCREEN = 16
>>> SM_CYFULLSCREEN = 17
>>>
>>> user32 = ct.windll.user32
>>> GetSystemMetrics = user32.GetSystemMetrics
>>>
>>> # @TODO: Never forget about the 2 lines below !!!
>>> GetSystemMetrics.argtypes = [ct.c_int]
>>> GetSystemMetrics.restype = ct.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:勾选.

如果您不想 window 持续存在,只需从 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))

How do I get monitor resolution in Python?