Python 如何使Tkinter GUI只打印Matplotlib图形一次

Python 如何使Tkinter GUI只打印Matplotlib图形一次,python,matplotlib,tkinter,canvas,figure,Python,Matplotlib,Tkinter,Canvas,Figure,我有一些Tkinter代码,它可以制作一个4ttabed gui。在GUI中,tab2有一个按钮来绘制一个简化的图形,它可以工作,但是当我再次单击该按钮时,它会在第一个绘图的正下方重新打印画布和图形。我已经了解了如何使用关闭或清除按钮删除绘图,但确实需要它只打印一次(即使再次单击按钮) 代码 所需输出 第二次按下绘图按钮不会导致图形显示在第一个绘图下方 来自xszym的想法 您可以通过设置全局标志was\u printed was_plotted = False def plot():

我有一些Tkinter代码,它可以制作一个4ttabed gui。在GUI中,tab2有一个按钮来绘制一个简化的图形,它可以工作,但是当我再次单击该按钮时,它会在第一个绘图的正下方重新打印画布和图形。我已经了解了如何使用关闭或清除按钮删除绘图,但确实需要它只打印一次(即使再次单击按钮)

代码

所需输出

第二次按下绘图按钮不会导致图形显示在第一个绘图下方

来自xszym的想法


您可以通过设置全局标志
was\u printed

was_plotted = False

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

关键是重用相同的
canvas
对象,但不要每次执行
plot
函数时都创建一个新的对象。我不知道如何做到这一点,我现在可以看到如何使用xszym提到的标志设置。该标志与重用同一对象无关,也没有帮助。只需将
画布
创建和
网格
方法移到函数之外,然后在
绘图
时,清除画布并在其上绘制。看看你是否仍然无法理解。嗨,Henry Yik,我用了你的想法,它成功了,如果你把你的评论作为答案转发,我会很乐意接受。
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
was_plotted = False

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