You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

多显示器环境下如何指定Matplotlib绘图到特定显示器?

固定Matplotlib图表到特定显示器的解决方案

Matplotlib窗口默认跟随鼠标所在显示器,要固定到指定显示器,核心是手动设置绘图窗口的初始位置,不同后端的实现略有差异,以下是两种常用后端的解决方法:

前置准备:获取显示器坐标

首先需要知道目标显示器的左上角坐标和尺寸,推荐用screeninfo库快速获取所有显示器信息:

pip install screeninfo

运行以下代码查看所有显示器的参数:

from screeninfo import get_monitors
print(get_monitors())

输出示例:

[Monitor(x=0, y=0, width=1920, height=1080, name='\\\\.\\DISPLAY1'), Monitor(x=1920, y=0, width=2560, height=1440, name='\\\\.\\DISPLAY2')]

根据输出的x、y坐标确定目标显示器的索引(比如第二台显示器索引为1)。


方法1:TkAgg后端(Matplotlib默认后端)

直接在创建Figure后设置Tkinter窗口的位置:

import matplotlib.pyplot as plt
from screeninfo import get_monitors

# 获取目标显示器信息
monitors = get_monitors()
target_monitor = monitors[1]  # 替换为你的目标显示器索引

# 创建绘图窗口并指定位置
fig = plt.figure(figsize=(10, 6))
window = fig.canvas.window()
# 设置窗口左上角坐标为目标显示器的左上角
window.wm_geometry(f"+{target_monitor.x}+{target_monitor.y}")

# 绘图示例
plt.plot([1, 2, 3], [4, 5, 1])
plt.title("固定在目标显示器的图表")
plt.show()

方法2:QtAgg后端(PyQt/PySide环境)

如果你的Matplotlib使用Qt后端,通过Qt窗口的setGeometry方法设置位置:

import matplotlib.pyplot as plt
from screeninfo import get_monitors
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg

# 获取目标显示器信息
monitors = get_monitors()
target_monitor = monitors[1]

# 创建绘图窗口并指定位置
fig = plt.figure(figsize=(10, 6))
canvas = FigureCanvasQTAgg(fig)
window = canvas.window()
# 参数:x坐标, y坐标, 窗口宽度, 窗口高度
window.setGeometry(target_monitor.x, target_monitor.y, 800, 600)

# 绘图示例
plt.plot([1, 2, 3], [4, 5, 1])
plt.title("固定在目标显示器的图表")
plt.show()

额外提示

  • 可以将获取显示器并设置窗口位置的逻辑封装成函数,避免重复代码;
  • 若使用Jupyter Notebook/Lab,该方法不适用(图表在浏览器内显示,而非桌面窗口);
  • 如果不想额外安装screeninfo,也可以用系统原生库(如Windows的ctypes、Linux的Xlib)获取显示器信息,但复杂度更高。

内容的提问来源于stack exchange,提问作者DmitryP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 20:11:27