如何使Tkinter GUI只绘制一次Matplotlib图

问题描述

我有一些Tkinter代码,可以编写4tabbed gui。在GUI tab2中有一个用于绘制简化图形的按钮,该按钮有效,但是当我再次单击该按钮时,它将在第一个图形的正下方重新打印画布和图形。我已经研究了如何使用“关闭”或“清除”按钮删除图,但确实需要它仅绘制一次(即使再次单击该按钮也是如此)。

代码

was_plotted = False

def plot():
    global was_plotted
    if(was_plotted) == False:
            # the figure that will contain the plot 
        fig = figure(figsize = (5,5),dpi = 100) 
        
        y = [i**2 for i in range(101)] # list of squares
        
        # adding the subplot 
        plot1 = fig.add_subplot(111) 
        # plotting the graph 
        plot1.plot(y) 
        canvas = figureCanvasTkAgg(fig,master = tab2)  # creating the Tkinter canvas containing the Matplotlib figure  
        canvas.draw() 
        canvas.get_tk_widget().grid()  # placing the canvas on the Tkinter window 

        
        was_plotted = True

所需的输出

再按一次Plot按钮不会导致图形出现在第一个图形下方。

来自xszym的

想法

Entry.objects.filter(pub_date__year=2005).order_by('-pub_date','headline')

解决方法

您可以通过设置全局标记was_plotted

来解决它
was_plotted = False

def plot():
    global was_plotted
    if(was_plotted):
        return 
    was_plotted = True