Skip to content Skip to sidebar Skip to footer

Plot Graph With Pyplot Using Input From Tkinter Spinbox

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 fo

Solution 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.


Post a Comment for "Plot Graph With Pyplot Using Input From Tkinter Spinbox"