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

标签 python matplotlib tkinter

我正在尝试确定当前 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(),那么出现警告的原因是什么?

最佳答案

这个警告是一个很大的谜团。使用交互模式时它总是出现。尽管有警告,但我在使用交互模式时从未遇到任何问题,因此我建议忽略它。这个方法看起来还不错。

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

这会打印图形宽度:640.0,高度: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))

打印例如屏幕宽度:1920,高度:1080

关于python - 如何在进入事件循环之前获取matplotlib图形窗口的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44100032/

相关文章:

python - 如何在 Python 中获取实时键盘输入?

Python 和 Matplotlib 的交互式缩放图

python - 如何创建具有精确单位和测量值的图

python - Tkinter 按钮不运行命令

python - 时间序列 Pandas 的线性回归

python - 在 Python 中将图例标签设置为日期

python - 为什么这个图像在 tkinter 中不显示?

python - 如何在Python中使整个窗口居中?

python - 带有键/值类型对的类型提示字典

python - 如何找到 cp 和 cp_p_g 在 M 轴上的交点?