【发布时间】:2015-10-15 03:57:47
【问题描述】:
一位程序员同事提醒我注意一个问题,即 matplotlib.pyplot 和 Tkinter 不能很好地协同工作,正如这个问题所证明的那样 Tkinter/Matplotlib backend conflict causes infinite mainloop
我们更改了代码以防止链接问题中提到的潜在问题,如下所示:
旧
import matplotlib.pyplot as plt
self.fig = plt.figure(figsize=(8,6))
if os.path.isfile('./UI.png'):
image = plt.imread('./UI.png')
plt.axis('off')
plt.tight_layout()
im = plt.imshow(image)
# The Canvas
self.canvas = FigureCanvasTkAgg(self.fig, master = master)
self.toolbar = NavigationToolbar2TkAgg(self.canvas, root)
self.canvas.get_tk_widget().pack(fill=BOTH,expand=YES)
self.canvas.draw()
中级(UI.png 未显示)
import matplotlib.pyplot as plt
import matplotlib
self.fig = matplotlib.figure.Figure(figsize=(8, 6))
if os.path.isfile('./UI.png'):
image = matplotlib.image.imread('./UI.png')
plt.axis('off')
plt.tight_layout()
plt.imshow(image)
# The Canvas
self.canvas = FigureCanvasTkAgg(self.fig, master=master)
self.toolbar = NavigationToolbar2TkAgg(self.canvas, root)
self.canvas.get_tk_widget().pack(fill=BOTH, expand=YES)
self.canvas.draw()
更改后的代码不再显示“背景”图像,我一直在尝试随机的东西(因为我对这两个选项之间的差异感到很迷茫)以再次显示图形。更改涉及从tight_layout 切换到set_tight_layout 以避免警告,如https://github.com/matplotlib/matplotlib/issues/1852 所述。结果代码如下:
可能的修复
import matplotlib.pyplot as plt
import matplotlib
self.fig = matplotlib.figure.Figure(figsize=(8, 6))
background_image = self.fig.add_subplot(111)
if os.path.isfile('./UI.png'):
image = matplotlib.image.imread('./UI.png')
background_image.axis('off')
#self.fig.tight_layout() # This throws a warning and falls back to Agg renderer, 'avoided' by using the line below this one.
self.fig.set_tight_layout(True)
background_image.imshow(image)
# The Canvas
self.canvas = FigureCanvasTkAgg(self.fig, master=master)
self.toolbar = NavigationToolbar2TkAgg(self.canvas, root)
self.canvas.get_tk_widget().pack(fill=BOTH, expand=YES)
self.canvas.draw()
因此问题是,为什么我们现在需要使用子图(使用 matplotlib.figure.Figure)而之前不需要(使用 matplotlib.pyplot)?
PS:如果这是一个愚蠢的问题,我很抱歉,但我能找到的关于这个主题的几乎所有东西似乎都使用了matplotlib.pyplot 变体。因此,我很难为 matplotlib.figure.Figure 变体找到任何好的文档。
【问题讨论】:
标签: python matplotlib tkinter