获取显示器分辨率的最简单方法是什么(最好是在元组中)?
答案 0 :(得分:96)
在Windows中,您还可以将ctypes与GetSystemMetrics()
:
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)
这样你就不需要安装pywin32包了; 它不需要Python本身没有的任何东西。
对于多显示器设置,您可以检索虚拟显示器的组合宽度和高度:
import ctypes
user32 = ctypes.windll.user32
screensize = user32.GetSystemMetrics(78), user32.GetSystemMetrics(79)
答案 1 :(得分:59)
我出于这个原因创建了PyPI module:
pip install screeninfo
代码:
from screeninfo import get_monitors
for m in get_monitors():
print(str(m))
结果:
monitor(1920x1080+1920+0)
monitor(1920x1080+0+0)
它支持多监视器环境。它的目标是跨平台;现在它支持Cygwin和X11,但拉取请求是完全受欢迎的。
答案 2 :(得分:53)
在Windows上:
from win32api import GetSystemMetrics
print("Width =", GetSystemMetrics(0))
print("Height =", GetSystemMetrics(1))
如果您使用的是高分辨率屏幕,请确保您的python解释器是HIGHDPIAWARE。
基于this帖子。
答案 3 :(得分:42)
如果你正在使用wxWindows,你可以这样做:
import wx
app = wx.App(False) # the wx.App object must be created first.
print(wx.GetDisplaySize()) # returns a tuple
答案 4 :(得分:33)
直接来自这篇文章的回答:How to get the screen size in Tkinter?
import tkinter as tk
root = tk.Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
答案 5 :(得分:19)
在Windows 8.1上,我无法从ctypes或tk获得正确的分辨率。 其他人对ctypes也有同样的问题:getsystemmetrics returns wrong screen size 要在Windows 8.1上获得高DPI监视器的正确完整分辨率,必须调用SetProcessDPIAware并使用以下代码:
import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
以下详细信息:
我发现这是因为Windows正在报告缩放分辨率。看来python默认是'system dpi aware'应用程序。此处列出了DPI感知应用程序的类型: http://msdn.microsoft.com/en-us/library/windows/desktop/dn469266%28v=vs.85%29.aspx#dpi_and_the_desktop_scaling_factor
基本上,不是显示内容的完整显示器分辨率,这会使字体变得很小,而是将内容放大,直到字体足够大。
在我的显示器上,我得到:
物理分辨率:2560 x 1440(220 DPI)
报告的python分辨率:1555 x 875(158 DPI)
根据此Windows网站:http://msdn.microsoft.com/en-us/library/aa770067%28v=vs.85%29.aspx 报告的系统有效分辨率的公式为: (reported_px * current_dpi)/(96 dpi)= physical_px
我可以使用以下代码获得正确的全屏分辨率和当前DPI。 请注意,我调用SetProcessDPIAware()以允许程序查看真实分辨率。
import tkinter as tk
root = tk.Tk()
width_px = root.winfo_screenwidth()
height_px = root.winfo_screenheight()
width_mm = root.winfo_screenmmwidth()
height_mm = root.winfo_screenmmheight()
# 2.54 cm = in
width_in = width_mm / 25.4
height_in = height_mm / 25.4
width_dpi = width_px/width_in
height_dpi = height_px/height_in
print('Width: %i px, Height: %i px' % (width_px, height_px))
print('Width: %i mm, Height: %i mm' % (width_mm, height_mm))
print('Width: %f in, Height: %f in' % (width_in, height_in))
print('Width: %f dpi, Height: %f dpi' % (width_dpi, height_dpi))
import ctypes
user32 = ctypes.windll.user32
user32.SetProcessDPIAware()
[w, h] = [user32.GetSystemMetrics(0), user32.GetSystemMetrics(1)]
print('Size is %f %f' % (w, h))
curr_dpi = w*96/width_px
print('Current DPI is %f' % (curr_dpi))
返回了:
Width: 1555 px, Height: 875 px
Width: 411 mm, Height: 232 mm
Width: 16.181102 in, Height: 9.133858 in
Width: 96.099757 dpi, Height: 95.797414 dpi
Size is 2560.000000 1440.000000
Current DPI is 158.045016
我正在运行带有220 DPI显示器的Windows 8.1。 我的显示缩放将当前的DPI设置为158。
我将使用158来确保我的matplotlib图是正确的尺寸: 来自pylab import rcParams rcParams ['figure.dpi'] = curr_dpi
答案 6 :(得分:15)
完整性,Mac OS X
import AppKit
[(screen.frame().size.width, screen.frame().size.height)
for screen in AppKit.NSScreen.screens()]
将为您提供包含所有屏幕大小的元组列表(如果存在多个监视器)
答案 7 :(得分:13)
如果您专门使用Qt
工具包PySide
,则可以执行以下操作:
from PySide import QtGui
import sys
app = QtGui.QApplication(sys.argv)
screen_rect = app.desktop().screenGeometry()
width, height = screen_rect.width(), screen_rect.height()
答案 8 :(得分:12)
使用Linux,最简单的方法是执行bash命令
xrandr | grep '*'
并使用regexp解析其输出。
你也可以通过PyGame:http://www.daniweb.com/forums/thread54881.html
来完成答案 9 :(得分:12)
这是一个快速的小Python程序,它将显示有关多显示器设置的信息:
import gtk
window = gtk.Window()
# the screen contains all monitors
screen = window.get_screen()
print "screen size: %d x %d" % (gtk.gdk.screen_width(),gtk.gdk.screen_height())
# collect data about each monitor
monitors = []
nmons = screen.get_n_monitors()
print "there are %d monitors" % nmons
for m in range(nmons):
mg = screen.get_monitor_geometry(m)
print "monitor %d: %d x %d" % (m,mg.width,mg.height)
monitors.append(mg)
# current monitor
curmon = screen.get_monitor_at_window(screen.get_active_window())
x, y, width, height = monitors[curmon]
print "monitor %d: %d x %d (current)" % (curmon,width,height)
以下是其输出的一个示例:
screen size: 5120 x 1200
there are 3 monitors
monitor 0: 1600 x 1200
monitor 1: 1920 x 1200
monitor 2: 1600 x 1200
monitor 1: 1920 x 1200 (current)
答案 10 :(得分:8)
我在我的一个项目中使用get_screen_resolution方法,如下面的那个,基本上是一个导入链。您可以根据需要修改此项,方法是删除那些不需要的部分,并在链中向上移动更多可能的端口。
PYTHON_V3 = sys.version_info >= (3,0,0) and sys.version_info < (4,0,0):
#[...]
def get_screen_resolution(self, measurement="px"):
"""
Tries to detect the screen resolution from the system.
@param measurement: The measurement to describe the screen resolution in. Can be either 'px', 'inch' or 'mm'.
@return: (screen_width,screen_height) where screen_width and screen_height are int types according to measurement.
"""
mm_per_inch = 25.4
px_per_inch = 72.0 #most common
try: # Platforms supported by GTK3, Fx Linux/BSD
from gi.repository import Gdk
screen = Gdk.Screen.get_default()
if measurement=="px":
width = screen.get_width()
height = screen.get_height()
elif measurement=="inch":
width = screen.get_width_mm()/mm_per_inch
height = screen.get_height_mm()/mm_per_inch
elif measurement=="mm":
width = screen.get_width_mm()
height = screen.get_height_mm()
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
return (width,height)
except:
try: #Probably the most OS independent way
if PYTHON_V3:
import tkinter
else:
import Tkinter as tkinter
root = tkinter.Tk()
if measurement=="px":
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
elif measurement=="inch":
width = root.winfo_screenmmwidth()/mm_per_inch
height = root.winfo_screenmmheight()/mm_per_inch
elif measurement=="mm":
width = root.winfo_screenmmwidth()
height = root.winfo_screenmmheight()
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
return (width,height)
except:
try: #Windows only
from win32api import GetSystemMetrics
width_px = GetSystemMetrics (0)
height_px = GetSystemMetrics (1)
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
try: # Windows only
import ctypes
user32 = ctypes.windll.user32
width_px = user32.GetSystemMetrics(0)
height_px = user32.GetSystemMetrics(1)
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
try: # Mac OS X only
import AppKit
for screen in AppKit.NSScreen.screens():
width_px = screen.frame().size.width
height_px = screen.frame().size.height
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
try: # Linux/Unix
import Xlib.display
resolution = Xlib.display.Display().screen().root.get_geometry()
width_px = resolution.width
height_px = resolution.height
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
try: # Linux/Unix
if not self.is_in_path("xrandr"):
raise ImportError("Cannot read the output of xrandr, if any.")
else:
args = ["xrandr", "-q", "-d", ":0"]
proc = subprocess.Popen(args,stdout=subprocess.PIPE)
for line in iter(proc.stdout.readline,''):
if isinstance(line, bytes):
line = line.decode("utf-8")
if "Screen" in line:
width_px = int(line.split()[7])
height_px = int(line.split()[9][:-1])
if measurement=="px":
return (width_px,height_px)
elif measurement=="inch":
return (width_px/px_per_inch,height_px/px_per_inch)
elif measurement=="mm":
return (width_px/mm_per_inch,height_px/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
except:
# Failover
screensize = 1366, 768
sys.stderr.write("WARNING: Failed to detect screen size. Falling back to %sx%s" % screensize)
if measurement=="px":
return screensize
elif measurement=="inch":
return (screensize[0]/px_per_inch,screensize[1]/px_per_inch)
elif measurement=="mm":
return (screensize[0]/mm_per_inch,screensize[1]/mm_per_inch)
else:
raise NotImplementedError("Handling %s is not implemented." % measurement)
答案 11 :(得分:6)
XWindows版本:
#!/usr/bin/python
import Xlib
import Xlib.display
resolution = Xlib.display.Display().screen().root.get_geometry()
print str(resolution.width) + "x" + str(resolution.height)
答案 12 :(得分:5)
请尝试以下代码:
import subprocess
resuls = subprocess.Popen(['xrandr'],stdout=subprocess.PIPE).communicate()[0].split("current")[1].split(",")[0]
width = resuls.split("x")[0].strip()
heigth = resuls.split("x")[1].strip()
print width + "x" + heigth
答案 13 :(得分:5)
旧问题但缺少这个问题。 我是python的新手,所以请告诉我这是否是一个“坏”的解决方案。 此解决方案仅适用于Windows和MacOS,它仅适用于主屏幕 - 但问题中未提及操作系统。
通过截屏来衡量尺寸。由于屏幕尺寸不应该改变,因此必须只进行一次。 如果你有一个像GTK,wx,...安装的gui工具包,那么有更优雅的解决方案。
请参阅Pillow
pip install Pillow
from PIL import ImageGrab
img = ImageGrab.grab()
print (img.size)
答案 14 :(得分:5)
如果您安装了PyQt4,请尝试以下代码:
from PyQt4 import QtGui
import sys
MyApp = QtGui.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))
对于PyQt5,以下内容将起作用:
from PyQt5 import QtWidgets
import sys
MyApp = QtWidgets.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))
答案 15 :(得分:3)
使用Linux 而不是regexp取第一行并取出当前的分辨率值。
当前显示分辨率:0
>>> screen = os.popen("xrandr -q -d :0").readlines()[0]
>>> print screen
Screen 0: minimum 320 x 200, current 1920 x 1080, maximum 1920 x 1920
>>> width = screen.split()[7]
>>> print width
1920
>>> height = screen.split()[9][:-1]
>>> print height
1080
>>> print "Current resolution is %s x %s" % (width,height)
Current resolution is 1920 x 1080
这是在xrandr 1.3.5上完成的,我不知道其他版本的输出是否不同,但这应该很容易弄明白。
答案 16 :(得分:2)
获取每像素位数:
import ctypes
user32 = ctypes.windll.user32
gdi32 = ctypes.windll.gdi32
screensize = (user32.GetSystemMetrics(0), user32.GetSystemMetrics(1))
print "screensize =%s"%(str(screensize))
dc = user32.GetDC(None);
screensize = (gdi32.GetDeviceCaps(dc,8), gdi32.GetDeviceCaps(dc,10), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
screensize = (gdi32.GetDeviceCaps(dc,118), gdi32.GetDeviceCaps(dc,117), gdi32.GetDeviceCaps(dc,12))
print "screensize =%s"%(str(screensize))
gdi32中的参数:
#/// Vertical height of entire desktop in pixels
#DESKTOPVERTRES = 117,
#/// Horizontal width of entire desktop in pixels
#DESKTOPHORZRES = 118,
#/// Horizontal width in pixels
#HORZRES = 8,
#/// Vertical height in pixels
#VERTRES = 10,
#/// Number of bits per pixel
#BITSPIXEL = 12,
答案 17 :(得分:2)
使用xrandr
的另一个版本:
import re
from subprocess import run, PIPE
output = run(['xrandr'], stdout=PIPE).stdout.decode()
result = re.search(r'current (\d+) x (\d+)', output)
width, height = map(int, result.groups()) if result else (800, 600)
答案 18 :(得分:2)
使用pygame:
import pygame
pygame.init()
infos = pygame.display.Info()
screen_size = (infos.current_w, infos.current_h)
但是,如果您尝试将窗口设置为屏幕大小,您可能只想这样做:
pygame.display.set_mode((0,0),pygame.FULLSCREEN)
将显示设置为全屏模式。 [2]
答案 19 :(得分:1)
尝试pyautogui:
import pyautogui
resolution = pyautogui.size()
print(resolution)
答案 20 :(得分:1)
许多答案都使用tkinter来查找屏幕的高度/宽度(分辨率),但是有时有必要知道您的屏幕跨平台兼容的 dpi 。 这个答案来自这个link,留下来作为对another post的评论,但是花了好几个小时才能找到。我还没有任何问题,但是如果它在您的系统上不起作用,请告诉我!
import tkinter
root = tkinter.Tk()
dpi = root.winfo_fpixels('1i')
文档说明:
winfo_fpixels(number)
# Return the number of pixels for the given distance NUMBER (e.g. "3c") as float
距离数字是一个数字,后跟一个单位,因此3c表示3厘米,此函数给出屏幕3厘米(as found here)上的像素数。 因此,要获得dpi,我们要求函数提供1英寸屏幕(“ 1i”)中的像素数。
答案 21 :(得分:0)
您可以使用PyMouse。要获取屏幕大小,只需使用screen_size()
属性:
from pymouse import PyMouse
m = PyMouse()
a = m.screen_size()
a
将返回一个元组(X, Y)
,其中X
是水平位置,Y
是垂直位置。
答案 22 :(得分:0)
在Linux上,我们可以使用子流程模块
IFNULL(column, NULL)
答案 23 :(得分:0)
对于视网膜屏幕来说有点麻烦,我使用tkinter来获取假尺寸,使用药丸抓斗来获取实际尺寸:
import tkinter
root = tkinter.Tk()
resolution_width = root.winfo_screenwidth()
resolution_height = root.winfo_screenheight()
image = ImageGrab.grab()
real_width, real_height = image.width, image.height
ratio_width = real_width / resolution_width
ratio_height = real_height/ resolution_height
答案 24 :(得分:0)
如果您使用的是Windows操作系统,则可以使用OS模块来获取它:
import os
cmd = 'wmic desktopmonitor get screenheight, screenwidth'
size_tuple = tuple(map(int,os.popen(cmd).read().split()[-2::]))
它将返回一个元组(Y,X),其中 Y 是水平尺寸, X 是垂直尺寸。这段代码适用于Python 2和Python 3
答案 25 :(得分:0)
扩展@user2366975的答案,以使用Tkinter(Python 2/3中的代码)在多屏幕设置中获取当前屏幕尺寸:
try:
# for Python 3
import tkinter as tk
except ImportError:
# for Python 2
import Tkinter as tk
def get_curr_screen_geometry():
"""
Workaround to get the size of the current screen in a multi-screen setup.
Returns:
geometry (str): The standard Tk geometry string.
[width]x[height]+[left]+[top]
"""
root = tk.Tk()
root.update_idletasks()
root.attributes('-fullscreen', True)
root.state('iconic')
geometry = root.winfo_geometry()
root.destroy()
return geometry
(应该可以跨平台工作,仅在Linux上进行测试)
答案 26 :(得分:0)
一个跨平台的简单方法是使用几乎所有python版本都附带的TKinter,因此您无需安装任何东西:
import tkinter
root = tkinter.Tk()
root.withdraw()
WIDTH, HEIGHT = root.winfo_screenwidth(), root.winfo_screenheight()
答案 27 :(得分:0)
对于更高版本的PyGtk:
storage.load({key: 'loginState'}).then(ret => {
this.setState({
user_id : ret.userid
})
})
.catch(err => {
console.warn(err.message);
});
答案 28 :(得分:0)
对于Linux,您可以使用以下代码:
import gi
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk
s = Gdk.Screen.get_default()
screen_width = s.get_width()
screen_height = s.get_height()
print(screen_width)
print(screen_height)
答案 29 :(得分:0)
使用pynput
库的实用程序脚本。在此处发布以供参考:
from pynput.mouse import Controller as MouseController
def get_screen_size():
"""Utility function to get screen resolution"""
mouse = MouseController()
width = height = 0
def _reset_mouse_position():
# Move the mouse to the top left of
# the screen
mouse.position = (0, 0)
# Reset mouse position
_reset_mouse_position()
count = 0
while 1:
count += 1
mouse.move(count, 0)
# Get the current position of the mouse
left = mouse.position[0]
# If the left doesn't change anymore, then
# that's the screen resolution's width
if width == left:
# Add the last pixel
width += 1
# Reset count for use for height
count = 0
break
# On each iteration, assign the left to
# the width
width = left
# Reset mouse position
_reset_mouse_position()
while 1:
count += 1
mouse.move(0, count)
# Get the current position of the mouse
right = mouse.position[1]
# If the right doesn't change anymore, then
# that's the screen resolution's height
if height == right:
# Add the last pixel
height += 1
break
# On each iteration, assign the right to
# the height
height = right
return width, height
>>> get_screen_size()
(1920, 1080)