【发布时间】:2020-09-09 17:58:10
【问题描述】:
我正在研究嵌入在 Python 中的 tkinter gui 中的 matplotlib 图。
首先创建一个FigureCanvasTkAgg,其中包括一个先前创建的对象,该对象包含一个matplotlib图形,然后绘制它。这部分工作得很好。 之后我想根据用户操作刷新画布/它的内容。如果调用刷新画布的方法,则刷新图形对象并重新绘制画布。 这也有效,图形已更新,但由于某种奇怪的原因,画布调整了大小,因此它缩小到原始大小的四分之一左右。如果我打印画布的大小,我可以看到它的大小发生了变化。
我尝试在刷新后将画布调整回原来的大小,但没有成功。
感谢您的任何意见。我添加了我的代码的缩短版本。
#canvas object which is displayed on the gui
class Canvas:
def __init__(self, parent):
#the map_figure object is create
self.map_figure = map_figure()
#the matplotlib figure is extracted from the map_figure
self.figure = self.map_figure.get_figure()
#the canvas is created using the figure and the parent
self.canvas = FigureCanvasTkAgg(self.figure, master=parent)
#I tried both, to manually set the canvas size to the window dimensions (which are
#described by w and h and using the .pack() parameters, both are working fine
self.canvas.get_tk_widget().config(width=w,height=h)
#self.canvas.get_tk_widget().pack(fill='both', expand=True)
self.canvas.get_tk_widget().pack()
#canvas is drawn
self.canvas.draw()
#its size is printed
print(self.get_size())
def refresh(self, parent, point):
#the map_figure of the canvas is refresh
self.map_figure.refresh(data)
#the matplotlib figure is extracted again
self.canvas.figure = self.map_figure.get_figure()
#canvas is redrawn
self.canvas.draw()
#the canvas size is now different for some reason even after calling
#self.canvas.get_tk_widget().config(width=w,height=h) before this again
print(self.canvas.get_width_height())
#the map_figure class if relevant
class map_figure:
def __init__(self, data):
self.figure = self.create_figure(data)
def get_figure(self):
return self.figure
def create_figure(self, data):
#creating a matplotlib figure, closing if there was one before
plt.close(fig=None)
fig = plt.figure()
#creating a figure using the data here
return fig
#refreshing the figure using new data
def refresh(self, data):
self.figure = self.create_figure(data)
这里还有两张图片来可视化我的问题:
【问题讨论】:
标签: python matplotlib canvas tkinter figure