微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Tkinter GUI中清除每个选项卡的画布

如何解决在Tkinter GUI中清除每个选项卡的画布

我有一个复杂的GUI,太长了,无法在此处发布。我无法理解如何从Tkinter gui中的图中清除图形。我有一个选项卡式gui,想在每个选项卡中绘制图形并在每个选项卡中清除图形。当我尝试执行此操作时,会遇到与画布有关的各种不同错误。我能理解一个图形,一个轴,一个制表符和一个框架,但是画布似乎被认为是一个图形的同义词,这个图形看起来很奇怪(而且可能不正确)。

我看不出图形和画布之间有什么区别(有吗?),我在这里阅读的大多数文章和答案似乎根本没有涵盖画布

Matplotlib文档: “数字 整个图。该图跟踪所有子轴,少量“特殊”艺术家(标题,图例等)和画布。 ( 不要太担心画布,这很关键 ,因为它实际上是绘制图形的对象,可以帮助您获得绘图,但对于用户而言,或多或少是您看不见的)。一个图形可以有任意数量的轴,但要有用,至少应有一个。”

代码

import tkinter.filedialog
import os
import re
import tkinter as tk                     
from tkinter import ttk 
import matplotlib
matplotlib.use("TkAgg")  # this is the backend of matplotlib
from matplotlib.backends.backend_tkagg import figureCanvasTkAgg,NavigationToolbar2Tk
from matplotlib.figure import figure
import matplotlib.animation as animation
from matplotlib import style
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import easygui
from matplotlib.legend_handler import HandlerLine2D
from scipy.stats import linregress
pd.set_option("display.max_rows",None,"display.max_columns",None)

#=====================================================================
# ROOT figURE FOR GUI
#=====================================================================
root = tk.Tk() 
root.title("Tab Widget")
root.geometry("600x450") 
tabControl = ttk.Notebook(root) 
tab1 = ttk.Frame(tabControl) 
tab2 = ttk.Frame(tabControl)
tabControl.add(tab1,text ='Circle cal drops')
tabControl.add(tab2,text ='OPW') 

tk.Grid.rowconfigure(root,weight=1)
tk.Grid.columnconfigure(root,weight=1)
tabControl.grid(column=0,row=0,sticky=tk.E+tk.W+tk.N+tk.S)


# TAB 1
# creating a frame (my_frame_1)
my_frame_1 = tk.Frame(tab1,bd=2,relief=tk.GROOVE)
my_frame_1.pack(side=tk.LEFT,anchor=tk.N,fill=tk.BOTH,expand=True)
#---------------------------------------------------------------------

fig = figure(figsize=(4,4),dpi=100)

def clearPlot():
    fig.clear()
    canvas.draw_idle()


def plotData():
    a = fig.add_subplot(111)
    a.plot([1,2,3,4,5],[5,6,1,8],marker='.',c='r')
    canvas = figureCanvasTkAgg(fig,master = my_frame_1)
    canvas.get_tk_widget().pack()
    canvas._tkcanvas.pack()


#create another frame(my_frame_2) 
my_frame_2 = tk.Frame(tab1,relief=tk.GROOVE)
my_frame_2.pack(side=tk.RIGHT)
#---------------------------------------------------------------------
button1_cal = tk.Button(my_frame_2,text = "Clear Plot",command = clearPlot,relief = tk.GROOVE,padx =20,pady =20 )
button1_cal.pack(side="top",fill="x")
button2_cal = tk.Button(my_frame_2,text = "Plot \nData",command = plotData,pady =20 )
button2_cal.pack(side="top",fill="x" )

# TAB 2
# creating a frame (my_frame_3)
my_frame_3 = tk.Frame(tab2,relief=tk.GROOVE)
my_frame_3.pack(side=tk.LEFT,expand=True)
#---------------------------------------------------------------------

def clearPlotOpw():
    pass

def plotDataOpw():
    fig = figure(figsize=(4,dpi=100)
    a = fig.add_subplot(111)
    a.plot([1,[8,5,11],marker='o',c='b')

    canvas = figureCanvasTkAgg(fig,master = my_frame_3)
    canvas.get_tk_widget().pack()

    canvas._tkcanvas.pack()

#create another frame(my_frame_4) 
my_frame_4 = tk.Frame(tab2,relief=tk.GROOVE)
my_frame_4.pack(side=tk.RIGHT)

button1_cal = tk.Button(my_frame_4,command = clearPlotOpw,fill="x")
button2_cal = tk.Button(my_frame_4,command = plotDataOpw,fill="x" )

root.mainloop()
print('\n'*4)

***期望的结果***

能够清除每个图并根据需要重新绘制图。

尝试使用清除绘图功能时的跟踪

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Users/.../opt/anaconda3/lib/python3.7/tkinter/__init__.py",line 1705,in __call__
    return self.func(*args)
  File "/Users/.../Desktop/tk_gui_grid/basic_08.py",line 48,in clearPlot
    canvas.draw_idle()
NameError: name 'canvas' is not defined

我知道画布是未定义的,但是当我定义画布时,绘图根本不会被绘制。

解决方法

这最终对我有用。

#MAKE A FIGURE OBJECT
my_figure4 = Figure(figsize = (4,4),dpi = 100) 

#MAKE A FRAME WIDGET
frame1 = tk.Frame(tab4,bd=2,relief=tk.GROOVE)
frame1.pack(side=tk.LEFT,anchor=tk.N,fill=tk.BOTH,expand=True)
frame2 = tk.Frame(tab4,relief=tk.GROOVE)
frame2.pack(side=tk.RIGHT)

#MAKE A CANVAS OBJECT
my_canvas4 = FigureCanvasTkAgg(my_figure4,master = frame1) # creating the Tkinter canvas containing the Matplotlib figure  

# TURN THE CANVAS OBJECT INTO A CANVAS WIDGET
my_canvas4.get_tk_widget().pack() # placing the canvas on the Tkinter window
my_canvas4.draw()

def plotData():
    plot1 = my_figure4.add_subplot(111) # adding the subplot 
    x = [1,2,3,4,5]
    y = [1,5]
    plot1.plot(x,y,marker='o',c='y')
    my_canvas4.draw()

def clearPlot():
    my_figure4.clear()
    my_canvas4.draw_idle()

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。