Ubuntu16.04 GNOME环境下Pygame获取当前显示器尺寸异常问题
解决Pygame在GNOME双屏环境下获取单个显示器尺寸的问题
这个问题我之前在Ubuntu GNOME的双屏环境下踩过坑!Pygame默认会把X11扩展桌面下的所有显示器当成一个超大的虚拟屏幕,所以pygame.display.Info()返回的是两个屏幕拼接后的总分辨率——比如你遇到的(3286, 1080)就是两个屏幕宽度加起来的结果。下面给你几个靠谱的解决办法:
方法一:用Xlib直接查询X11显示器信息
Xlib可以直接和X窗口系统交互,能精准获取每个显示器的参数(包括位置和尺寸)。首先得安装依赖:
sudo apt-get install python-xlib
然后用下面的代码获取当前鼠标所在显示器的尺寸(这样能准确对应你正在操作的屏幕):
from Xlib import display def get_current_monitor_size(): d = display.Display() root = d.screen().root # 获取当前鼠标位置 mouse_data = root.query_pointer()._data mouse_x, mouse_y = mouse_data['root_x'], mouse_data['root_y'] # 遍历所有显示器输出 screen_resources = d.screen().root.xrandr_get_screen_resources() for output in screen_resources.outputs: output_info = d.xrandr_get_output_info(output, screen_resources.config_timestamp) if output_info.crtc: crtc_info = d.xrandr_get_crtc_info(output_info.crtc, 0) # 显示器的位置和尺寸 crtc_x, crtc_y = crtc_info.x, crtc_info.y crtc_w, crtc_h = crtc_info.width, crtc_info.height # 判断鼠标是否在这个显示器范围内 if crtc_x <= mouse_x < crtc_x + crtc_w and crtc_y <= mouse_y < crtc_y + crtc_h: return (crtc_w, crtc_h) # 如果没找到,返回主屏幕尺寸 return (d.screen().width_in_pixels, d.screen().height_in_pixels) # 调用函数获取尺寸并创建窗口 current_w, current_h = get_current_monitor_size() screen = pygame.display.set_mode((current_w, current_h))
方法二:借助GTK库获取当前显示器
因为GNOME基于GTK,用GTK的API可以轻松获取系统的显示器信息,兼容性更好。先安装依赖:
sudo apt-get install python-gi
然后用这段代码:
from gi.repository import Gdk import pygame def get_current_monitor_size(): display = Gdk.Display.get_default() screen = display.get_default_screen() # 创建临时窗口来定位当前显示器 temp_window = Gdk.Window.new(None, 0, 0, 0, 0, Gdk.WindowType.TEMP) temp_window.set_position(Gdk.WindowPosition.CENTER) # 获取窗口所在的显示器索引 monitor_idx = screen.get_monitor_at_window(temp_window) # 获取该显示器的几何信息 monitor_geo = screen.get_monitor_geometry(monitor_idx) return (monitor_geo.width, monitor_geo.height) # 使用示例 current_w, current_h = get_current_monitor_size() screen = pygame.display.set_mode((current_w, current_h))
为什么会出现这个问题?
在GNOME的默认设置里,双屏会被配置成“扩展桌面”模式,X11窗口系统会把多个显示器合并成一个虚拟的大屏幕。Pygame的display.Info()函数直接读取了这个虚拟屏幕的参数,所以才会得到两个屏幕的总宽度。
内容的提问来源于stack exchange,提问作者Isky
相关产品推荐
相关产品推荐

