tkinter图形(带有色条)每次显示时都会缩小

问题描述 投票:0回答:1

这是一个tkinter程序,是从我正在使用的GUI上精炼下来的:

import tkinter as tk
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import (
    FigureCanvasTkAgg, NavigationToolbar2Tk)

class App(tk.Tk):
    def __init__(self):
        super(App, self).__init__()
        self.main_frame = tk.Frame(self,)
        self.main_frame.pack(fill=tk.BOTH, expand=1)

        self.plot1_button = tk.Button(self.main_frame, text='Plot 1',
                                      command=self.draw_plot1)
        self.plot1_button.pack(fill=tk.X,expand=1)

        self.plot2_button = tk.Button(self.main_frame, text='Plot 2',
                                      command=self.draw_plot2)
        self.plot2_button.pack(fill=tk.X,expand=1)

        self.FIG, self.AX = plt.subplots()
        self.canvas = FigureCanvasTkAgg(self.FIG, master=self.main_frame)   
        self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
        self.toolbar = NavigationToolbar2Tk(self.canvas, self.main_frame)
        self.canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand=1)

    def draw_plot1(self):
        self.clear_axes()
        fig = self.AX.plot(np.random.rand(10),np.random.rand(10), color='red')
        self.canvas.draw_idle()
        self.toolbar.update()      

    def draw_plot2(self):
        self.clear_axes()
        im = self.AX.matshow(np.random.rand(100,100))
        self.canvas.draw_idle()
        self.toolbar.update()
        cb = plt.colorbar(im, ax=self.AX)

    def clear_axes(self):
        for ax in self.FIG.axes:
            ax.clear()
            if ax != self.AX:
                ax.remove()
root = App()
root.resizable(False, False)
root.mainloop()

Plot 1按钮绘制随机线图,而Plot 2按钮绘制带有色条的随机热图。可以重复单击“图1”按钮,从而按预期创建新的随机线图。单击10次后,显示看起来很好:

Plot 1 after 10 clicks

但是Plot 2按钮使图形每次单击都会缩小。单击10次后,该图将无法解释:

enter image description here

此外,再次单击图1时,图形大小仍然存在:

enter image description here

这些是从应用程序的工具栏保存的.png文件,但在GUI窗口中也可以看到。我曾尝试在其他位置向GUI /画布(例如self.update()self.canvas.draw_idle())添加更新,但没有发现任何会影响此问题的内容。我添加了clear_axes()函数,因为在实际的GUI中,我有一些具有多个axes的图形,因此将它们删除了,但显然在这里没有帮助。

[我发现如果删除了颜色条,问题就消失了](即注释掉cb = plt.colorbar(im, ax=self.AX)),但我希望将此作为图表的一部分。谁能阐明正在发生的事情,或者有人可以提出解决方案?我在matplotlib 3.2.1上。

python matplotlib tkinter colorbar
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.