问题的原因是有时候写的脚本需要在不同分辨率的显示器上显示,如果把matplotlib的输出设置成全都一样,一些情况下的显示将会比较奇怪。因此首先探测显示器分辨率然后再设置显示窗口的大小有时候是必要的。
得到屏幕分辨率的方式有很多,最简单可以直接从matplotlib提供的函数中获得
import matplotlib.pyplot as plt window = plt.get_current_fig_manager().window screen_y = window.winfo_screenheight() screen_x = window.winfo_screenwidth()
但是在我的manjaro系统上执行上述语句会报错,Ubuntu系统就没有问题。后来我才意识到原来是因为manjaro系统默认的matplotlib后端是 Qt5Agg ,前述的winfo_screenheight() 函数实际上是Tkinter提供的函数
import Tkinter root = Tkinter.Tk() width = root.winfo_screenwidth() height = root.winfo_screenheight()
参见:https://www.blog.pythonlibrary.org/2015/08/18/getting-your-screen-resolution-with-python/
如果想要使用上述函数,需要在导入pyplot之前将matplotlib后端设置成TkAgg
import matplotlib matplotlib.use('TkAgg')
但是有时候你可能并不想修改默认的后端,那么针对Qt5Agg我们可以通过下述的方法来得到屏幕分辨率
import sys from PyQt5 import QtWidgets app = QtWidgets.QApplication(sys.argv) screen = app.primaryScreen() print('Screen: %s' % screen.name()) size = screen.size() print('Size: %d x %d' % (size.width(), size.height()))
参加:https://stackoverflow.com/questions/35887237/current-screen-size-in-python3-with-pyqt5
除了这些从特定绘图包调用函数得到屏幕分辨率外,还可以直接使用screeninfo包来解决这个问题,首先安装screeninfo
pip install screeninfo
调用就很简单
from screeninfo import get_monitors monit = get_monitors()[0] print(monit.width) print(monit.height)
除此之外,最简单的,我们还可以直接调用系统命令来得到屏幕尺寸
import os com = os.popen("xrandr | grep \* | cut -d' ' -f4") res = com.read() width, height = [int(i) for i in res.strip().split('x')] print(width, height)
以下网页有非常详细的示例:
https://stackoverflow.com/questions/3129322/how-do-i-get-monitor-resolution-in-python
起它还可参考:
https://www.blog.pythonlibrary.org/2015/08/18/getting-your-screen-resolution-with-python/
在得到屏幕尺寸后可以就可以轻易规划窗口显示大小了
import matplotlib.pyplot as plt fig = plt.gcf() dpi = fig.dpi swidth, sheight = getscreenresolution() swidth, sheight = swidth/dpi, sheight/dpi fig = plt.figure(swidth/2, sheight/2)
参见:https://stackoverflow.com/questions/29702424/how-to-get-matplotlib-figure-size
切换matplotlib后端的几种方法参见: 关于matplotlib的后端(Backend)
Visits: 395