0

I want to handle a plot window with some Tkinter buttons. Like for example plot matrix columns and switch columns with buttons. I ve tried this :

import numpy
import pylab
import Tkinter

pylab.ion()
# Functions definitions:
x = numpy.arange(0.0,3.0,0.01)
y = numpy.sin(2*numpy.pi*x)
Y = numpy.vstack((y,y/2,y/3,y/4))

#Usual plot depending on a parameter n:
def graphic_plot(n):
    if n < 0: n = 0
    if n > len(Y): n = len(Y)-1
    fig = pylab.figure(figsize=(8,5))
    ax = fig.add_subplot(111)
    ax.plot(x,Y[n,:],'x',markersize=2)
    ax.set_xlabel('x title')
    ax.set_ylabel('y title')
    ax.set_xlim(0.0,3.0)
    ax.set_ylim(-1.0,1.0)
    ax.grid(True)
    pylab.show()


def increase(n):
   return n+1

def decrease(n):
    return n-1

n=0
master = Tkinter.Tk()
left_button  = Tkinter.Button(master,text="<",command=decrease(n))
left_button.pack(side="left")
right_button = Tkinter.Button(master,text=">",command=increase(n))
right_button.pack(side="left")
master.mainloop()

But I dont't know when to call the graphic_plot function and refresh the graphic correspondingly to the nparameter.

1 Answer 1

1

First off, you need to pass a function to the command parameter in buttons. In this code,

left_button  = Tkinter.Button(master, text="<", command=decrease(n))

you're handing decrease(0), or -1, to command.


Other problems:

  • we can't just pass in decrease because it takes a parameter
  • n's state is never changed
  • the plot should be updated whenever n is inced/deced

We can easily solve these problems by moving n into a class with a couple of methods:

class SimpleModel:

  def __init__(self):
    self.n = 0

  def increment(self):
    self.n += 1
    graphic_plot(self.n)

  def decrement(self):
    self.n -= 1
    graphic_plot(self.n)

Then for the buttons, we'll have:

model = SimpleModel()  # create a model

left_button  = Tkinter.Button(master, text="<", command=model.decrease)

right_button = Tkinter.Button(master, text=">", command=model.increase)
Sign up to request clarification or add additional context in comments.

Comments

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.