2012-04-04 26 views
0

我想用一些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() 

但我dont't知道何时调用graphic_plot功能,并相应地刷新图片给n参数。

回答

1

首先,您需要pass a functioncommand按钮中的参数。在这段代码中,

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

你交给decrease(0),或-1,以command


其他问题:

  • 我们不能只是传递decrease,因为这需要一个参数
  • n的状态没有改变
  • 情节应该被更新时n是Inced/deced

我们可以很容易地解决这些问题EMS通过移动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)