进入事件循环前如何获取matplotlib图形窗口的宽度?

2024-04-26 20:24:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图确定当前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()

输出为:

^{pr2}$

如果我取消了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(),那么发出警告的原因是什么?在

Tags: noinfoeventmatplotlibshowfigpltwindow
1条回答
网友
1楼 · 发布于 2024-04-26 20:24:39

这个警告是个大谜团。当使用交互模式时,它总是出现。尽管有警告,我在使用交互模式时从未遇到任何问题,所以我建议忽略它。这个方法似乎还可以。在

另一种获得图形大小的方法是(参见this question) 用dpi(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

^{pr2}$

例如screen width: 1920, height: 1080。在

相关问题 更多 >