【问题标题】:Handle plot with Tkinter用 Tkinter 处理情节
【发布时间】:2012-04-04 11:49:16
【问题描述】:

我想用一些 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参数的图形。

【问题讨论】:

    标签: python matplotlib tkinter


    【解决方案1】:

    首先,您需要将pass a function 设置为按钮中的command 参数。在这段代码中,

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

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


    其他问题:

    • 我们不能只传入decrease,因为它需要一个参数
    • n 的状态永远不会改变
    • 应该在 n 被 inced/deced 时更新绘图

    我们可以通过将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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-19
      • 1970-01-01
      • 2011-05-18
      • 1970-01-01
      • 2022-01-05
      • 2020-09-28
      • 2021-12-22
      • 1970-01-01
      相关资源
      最近更新 更多