是否有内置函数或直接方法来获得Python中最大化窗口的分辨率(例如,在没有任务栏的Windows全屏上(?我已经尝试了其他帖子中的一些内容,这些内容存在一些主要的缺点:
- ctypes
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(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((的循环。手动关闭窗口当然不是一种选择。
- 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]
,我发现这非常不一致!(正如你所能想象的,必须进行交互才能获得最终价值绝对不是一种选择。(
根据[MS.Docs]:GetSystemMetrics函数(emphasis是我的(:
SM_CXFULLSCREEN
16
主显示监视器上全屏窗口的客户端区域宽度 ,以像素为单位。要获取未被系统任务栏或应用程序桌面工具栏遮挡的屏幕部分的坐标,请使用SPI_GETWORKRAREA值调用SystemParametersInfo函数。
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:check[SO]:从Python通过ctypes调用的C函数返回错误值(@CristiFati的答案(。
如果不希望窗口持久化,只需从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中获得监视器分辨率?