我正在尝试确定当前matplotlib图形窗口的大小,以便我可以在屏幕上正确地重新定位它。这必须在进入事件循环之前完成(即在调用plt.show()
之前)。这是一个例子:
import matplotlib
import matplotlib.pyplot as plt
def print_info(window):
print("screen width: {}".format(window.winfo_screenwidth()))
print("window width: {}".format(window.winfo_width()))
return
matplotlib.use('TkAgg')
fig, axes = plt.subplots()
axes.plot([1, 2, 3], [1, 4, 9], 'ro', label='Test')
axes.set_title('Test curve')
# plt.draw() # <-- this has no effect
# fig.canvas.draw_idle() # <-- this has no effect
window = plt.get_current_fig_manager().window
# window.update() # <-- this has no effect
fig.canvas.mpl_connect('key_press_event', lambda event: print_info(window))
#plt.pause(0.000001) # only entering the tk/pyplot event loop forces update
print_info(window)
plt.show()
输出结果为:
screen width: 1920
window width: 1
如果我取消注释plt.pause(...)
电话,它可以正常工作(但我会收到警告):
/home/hakon/.pyenv/versions/3.6.1/lib/python3.6/site-packages/matplotlib/backend_bases.py:2453: MatplotlibDeprecationWarning: Using default event loop until function specific to this GUI is implemented
warnings.warn(str, mplDeprecation)
screen width: 1920
window width: 640
plt.pause()
来获得正确的窗口宽度?plt.pause()
,那么警告的原因是什么?答案 0 :(得分:2)
这个警告是一个很大的谜。使用交互模式时始终显示。尽管有警告,我从未遇到使用交互模式的任何问题,所以我建议忽略它。方法似乎没问题。
获得数字大小的另一种方法是(见this question)
将数字大小(英寸(fig.get_size_inches()
)乘以dpi(fig.dpi
)。
import matplotlib
matplotlib.use('TkAgg') # <- note that this must be called before pyplot import.
import matplotlib.pyplot as plt
fig, axes = plt.subplots()
axes.plot([1, 2, 3], [1, 4, 9], 'ro', label='Test')
axes.set_title('Test curve')
size = fig.get_size_inches()*fig.dpi
print("figure width: {}, height: {}".format(*size))
plt.show()
这会打印figure width: 640.0, height: 480.0
,默认设置为6.4和4.8英寸以及100 dpi。
要查找屏幕宽度和高度,您可以使用例如Tkinter的
import Tkinter as tk # use tkinter for python 3
root = tk.Tk()
width = root.winfo_screenwidth()
height = root.winfo_screenheight()
print("screen width: {}, height: {}".format(width, height))
打印例如screen width: 1920, height: 1080
。