用Tkinter处理情节

时间:2012-04-04 11:49:16

标签: python matplotlib tkinter

我想用一些Tkinter按钮处理一个绘图窗口。例如,绘图矩阵列和带按钮的切换列。我试过这个:

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()

但我不知道何时调用graphic_plot函数并相应地刷新n参数。

1 个答案:

答案 0 :(得分:1)

首先,您需要pass a function到按钮中的command参数。在此代码中,

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

您将decrease(0)或-1交给command


其他问题:

  • 我们不能只传递decrease,因为它需要一个参数
  • n的状态永远不会改变
  • 每当n被引入/提升
  • 时,应更新图表

我们可以通过几种方法将n移动到一个类中来轻松解决这些问题:

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)

然后对于按钮,我们将:

model = SimpleModel()  # create a model

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

right_button = Tkinter.Button(master, text=">", command=model.increase)