1

The image shows the GUI: enter image description here

  1. I am making a GUI with Tkinter which can show graphs which have been plotted with matplotlib.
  2. The graphs get their x and y values from a JSON file.
  3. The data from the JSON file gets collected by some code which I wrote (this code is included in the code below)

What works: The collecting of data from the JSON-file, plotting the data in a graph via matplotlib, and showing this graph on a tkinter canvas all works fine.

Problem: I cannot clear the canvas, such that I can display another graph based on data from another JSON file. I have to close the program, start it again, and select a different JSON file, if I want to see another graph.

Here is the code:

################################### GUI program for graphs #######################################

##### Scrollbar for the listbox #####
Myframe = Frame(inspect_data)
Myframe.pack(side=tk.LEFT, fill=Y)
my_scrollbar = Scrollbar(Myframe, orient=VERTICAL)

#####Listbox#####
vores_listebox = Listbox(Myframe, width=22, height=40,
                         yscrollcommand=my_scrollbar.set)
vores_listebox.pack(side=LEFT, expand=True)

my_scrollbar.config(command=vores_listebox.yview)
my_scrollbar.pack(side=LEFT, fill=Y)
Myframe.pack()


###### Button functions ######
path_us = ""


def vis_NS():
    vores_listebox.delete(0, END)
    # Husk at ændre mapper##
    global path_us
    path_us = "C://Users//canal//OneDrive//Dokumenter//AAU//3. semester//1//"
    for x in os.listdir(path_us):
        if x.endswith(".json"):
            vores_listebox.insert(END, x)


def vis_OS():
    global path_us
    path_us = "C://Users//canal//OneDrive//Dokumenter//AAU//3. semester//2//"
    vores_listebox.delete(0, END)
    # De NS;OS,US,MS skal ligge i hver sin mappe#
    for x in os.listdir(path_us):
        if x.endswith(".json"):
            vores_listebox.insert(END, x)


def vis_US():
    vores_listebox.delete(0, END)
    for x in os.listdir("C://Users//canal//OneDrive//Dokumenter//AAU//3. semester//2"):
        if x.endswith(".json"):
            vores_listebox.insert(END, x)


def vis_MS():
    vores_listebox.delete(0, END)
    for x in os.listdir("C://Users//canal//OneDrive//Dokumenter//AAU//3. semester//2"):
        if x.endswith(".json"):
            vores_listebox.insert(END, x)


#### Buttons #####
button1 = Button(inspect_data,
                 text="Normal screwing",
                 width=17,
                 height=2,
                 bg="white",
                 fg="black",
                 command=vis_NS
                 )
button1.place(x=5, y=10)

button2 = Button(inspect_data,
                 text="Over screwing",
                 width=17,
                 height=2,
                 bg="white",
                 fg="black",
                 command=vis_OS
                 )
button2.place(x=5, y=50)

button3 = Button(inspect_data,
                 text="Under screwing",
                 width=17,
                 height=2,
                 bg="white",
                 fg="black",
                 command=vis_US
                 )
button3.place(x=5, y=90)

button4 = Button(inspect_data,
                 text="Missing screw",
                 width=17,
                 height=2,
                 bg="white",
                 fg="black",
                 command=vis_MS
                 )
button4.place(x=5, y=130)

######en fil bliver trykket#####

# placing the canvas on the Tkinter window


def items_selected(event):
    selected_indices = vores_listebox.curselection()

    selected_json = ",".join([vores_listebox.get(i) for i in selected_indices])
    full_file_path = path_us + selected_json
    open_json = js.load(open(full_file_path, "r"))
    time = [open_json['XML_Data']
            ['Wsk3Vectors']['X_Axis']['Values']['float']]
    rpm = [open_json['XML_Data']['Wsk3Vectors']
           ['Y_AxesList']['AxisData'][0]['Values']['float']]
    torque = [open_json['XML_Data']['Wsk3Vectors']
              ['Y_AxesList']['AxisData'][1]['Values']['float']]
    current = [open_json['XML_Data']['Wsk3Vectors']
               ['Y_AxesList']['AxisData'][2]['Values']['float']]
    angle = [open_json['XML_Data']['Wsk3Vectors']
             ['Y_AxesList']['AxisData'][3]['Values']['float']]
    depth = [open_json['XML_Data']['Wsk3Vectors']
             ['Y_AxesList']['AxisData'][4]['Values']['float']]


####### Using Matlib.pyplot to plot 5 graphs #######
    plt.rcParams["figure.figsize"] = (7, 10)

    plt.subplot(5, 1, 1)
    plt.scatter(time, rpm, c="b", linewidths=2,
                marker=",", edgecolor="b", s=1, alpha=0.5)
    plt.title(selected_json)
    plt.gca().axes.xaxis.set_ticklabels([])
    plt.ylabel("RPM")
    plt.grid()

    plt.subplot(5, 1, 2)
    plt.scatter(time, torque, c="g", linewidths=1,
                marker=",", edgecolor="g", s=1, alpha=0.3)
    plt.gca().axes.xaxis.set_ticklabels([])
    plt.ylabel("Torque [Nm]")
    plt.grid()

    plt.subplot(5, 1, 3)
    plt.scatter(time, current, c="r", linewidths=2,
                marker=",", edgecolor="r", s=1, alpha=0.5)
    plt.gca().axes.xaxis.set_ticklabels([])
    plt.ylabel("Current [Amps]")
    plt.grid()

    plt.subplot(5, 1, 4)
    plt.scatter(time, angle, c="m", linewidths=2,
                marker=",", edgecolor="m", s=1, alpha=0.5)
    plt.gca().axes.xaxis.set_ticklabels([])
    plt.ylabel("Angle [RAD]")
    plt.grid()

    plt.subplot(5, 1, 5)
    plt.scatter(time, depth, c="c", linewidths=2,
                marker=",", edgecolor="c", s=1, alpha=0.5)
    plt.xlabel("Time [ms]")
    plt.ylabel("Depth [mm]")
    plt.grid()

    #### Sowing all the subplots in a tkinter canvas ########

    fig = plt.figure()
    canvas = FigureCanvasTkAgg(fig, master=inspect_data)
    canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
    # toolbar = matplotlib.NavigationToolbar2TkAgg(
    #    canvas, self)
    # toolbar.update()
    canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)


vores_listebox.bind('<<ListboxSelect>>', items_selected)

root.after(1000, converter)
root.mainloop()

I have tried canvas.delete(all), plt.clf() among other things. One solution I think could work is:

If I start the function def items_selected to clear the figure inside the canvas by using: plt.clf(fig), however "fig" is not defined at this point, so python wouldn't know what this means.

1 Answer 1

0

it seems to me that the problem originates from plotting to plt, and not directly onto some axis from a figure linked to tkinter. Try to bind your subplot figure directly to your canvas outside the items_selected() function, and then redraw the canvas whenever you change the underlying matplotlib figure:

fig, axes = plt.subplots(5, 1, figsize=(7, 10))
canvas = FigureCanvasTkAgg(fig, inspect_data)
canvas.get_tk_widget().pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

def items_selected(event):
    .....
    axes[0].scatter(time, rpm, c="b", linewidths=2,
                marker=",", edgecolor="b", s=1, alpha=0.5)
    axes[0].set_title(selected_json)
    axes[0].set_xticklabels([])
    axes[0].set_ylabel("RPM")
    axes[0].grid()
    .... 
   
    canvas.draw()
1
  • I tried, but with no succes. I have now resorted to using plt.show(), which works fine. But this always displays a small window which i have to manually resize to my liking. Nov 15, 2022 at 12:56

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.