0

I am working in a project which needs to plot a graph dynamically as the inputs in a tkinter spinbox is changed.

I have a sample code:

from tkinter import *
from tkinter import font
from tkinter.font import Font
from tkinter import messagebox
print("'Tkinter' module is found as tkinter.")

import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.backend_bases import key_press_handler
from matplotlib.figure import Figure
print("Importing matplotlib from libraries.")


master = Tk()

def ok(x_val=1000,y_val=20):
         fig = Figure(figsize=(5,5),dpi=70)
         ax = fig.subplots()
         ax.set_title("Right Ear")
         ax.set_ylabel("db HL")
         ax.set_xlabel("Frequency")
         ax.set_xlim(100,9000)
         ax.set_ylim(130,-10)
         ax.set_facecolor("#ffd2d2")

         x = [125,250,500,1000,2000,4000,8000]
         ticks = [125,250,500,"1K","2K","4K","8K"]
         xm = [750,1500,3000,6000]

         ax.set_xscale('log', basex=2)
         ax.set_xticks(x)
         ax.set_xticks(xm, minor=True)
         ax.set_xticklabels(ticks)
         ax.set_xticklabels([""]*len(xm), minor=True)


         ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])


         ax.plot([x_val],[y_val],'r+',markersize=15.0,mew=2)
         ax.grid(color="grey")
         ax.grid(axis="x", which='minor',color="grey", linestyle="--")
         canvas = FigureCanvasTkAgg(fig, master=master)
         canvas.show()
         canvas.get_tk_widget().grid(column=0,row=2,columnspan=3,rowspan=15)

def action():
        print(spin.get())
        canvas.draw()
        ok(spin.get(),10)

spin = Spinbox(master, from_=125,to=8000,command=action)
spin.grid(column=5,row=2)

ok()

This code does not change the plot, I cannot understand how to change it, to be precise, how to use canvas.draw() here to do the work. The spinbox has value range from 125 to 8000, I could not figure out how to take the value of the spinbox every time it changes (can use command= but how to implement) and feed it to the x axis of ax.plot() and plot dynamically. As the value of spinbox changes the plot also changes to the new position and removes the previous plot from the previous position.

1 Answer 1

1

You need to make the variables you need available. A usual approach is to use a class and make those class variables. Those can then be accessed from within the class (self) or outside as attributes.

from Tkinter import *

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure

class PlotClass():
    def __init__(self):
         fig = Figure(figsize=(5,5),dpi=70)
         ax = fig.subplots()
         ax.set_title("Right Ear")
         ax.set_ylabel("db HL")
         ax.set_xlabel("Frequency")
         ax.set_xlim(100,9000)
         ax.set_ylim(130,-10)
         ax.set_facecolor("#ffd2d2")

         x = [125,250,500,1000,2000,4000,8000]
         ticks = [125,250,500,"1K","2K","4K","8K"]
         xm = [750,1500,3000,6000]

         ax.set_xscale('log', basex=2)
         ax.set_xticks(x)
         ax.set_xticks(xm, minor=True)
         ax.set_xticklabels(ticks)
         ax.set_xticklabels([""]*len(xm), minor=True)

         ax.yaxis.set_ticks([120,110,100,90,80,70,60,50,40,30,20,10,0,-10])

         self.line, = ax.plot([],[],'r+',markersize=15.0,mew=2)
         ax.grid(color="grey")
         ax.grid(axis="x", which='minor',color="grey", linestyle="--")
         self.canvas = canvas = FigureCanvasTkAgg(fig, master=master)
         canvas.show()
         canvas.get_tk_widget().grid(column=0,row=2,columnspan=3,rowspan=15)
         self.spin = Spinbox(master, from_=125,to=8000,command=self.action)
         self.spin.grid(column=5,row=2)

    def ok(self, x=1000,y=20):
        self.line.set_data([x],[y])
        self.canvas.draw_idle()

    def action(self):
        self.ok(float(self.spin.get()),10)

master = Tk()
plotter = PlotClass()
plotter.ok(125,10)
master.mainloop()

Note: In newer versions of matplotlib you should use NavigationToolbar2Tk instead of NavigationToolbar2TkAgg.

Sign up to request clarification or add additional context in comments.

1 Comment

I asked another question based on @ImportanceOfBeingErnest your answer. [here] (stackoverflow.com/questions/47843511/…)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.