Tkinter spinbox textvariable

时间:2012-02-14 21:53:03

标签: python tkinter

我正在尝试在Tkinter中创建一个简单的GUI来显示一些xy数据。数据在试验中排列,目标是有一个旋转框,允许您选择要查看的试验。我不明白为什么但是在下面的代码中textvariable的值没有更新,所以我总是最终查看相同的试用版。有什么明显的东西让我失踪吗?代码如下。 Tk.IntVar在 init 中设置,与spinbox(非常底部)相关联,并在updateDataToPlot中使用。

#graphing stuff
import matplotlib
matplotlib.use('TkAgg')
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
from matplotlib.figure import Figure
from matplotlib.lines import Line2D
import Tkinter as Tk

import numpy as np
import matplotlib.pyplot as plt
from scipy import randn
from collections import defaultdict

class DataPlotter:
    def __init__(self, ax, data):

        self.ax = ax
        self.canvas = ax.figure.canvas
        self.data = data

        self.xRaw = []
        self.yRaw = []

        self.lineRaw = Line2D(self.xRaw, self.yRaw, animated=True, marker = None, color = 'black')
        self.ax.add_line(self.lineRaw)

        self.background = None
        self.canvas.mpl_connect('draw_event', self.updateBackground)
        self.ax.set_ylim(-3,3)
        self.ax.set_xlim(-3,3)

        self.ax.set_xlabel('X Pos (mm)')
        self.ax.set_ylabel('Y Pos (mm)')

        self.TrialNum = Tk.IntVar()
        self.TrialNum.set(0)

    def updateBackground(self, event):
        self.background = self.canvas.copy_from_bbox(self.ax.bbox)

    def updateDataToPlot(self):
        trialNum = self.TrialNum.get()
        print trialNum

        self.xRaw = self.data['polaris_rawPositions'][trialNum][:,0]
        self.yRaw = self.data['polaris_rawPositions'][trialNum][:,1]

        self.updateView()

    def updateView(self):
        if self.background is None: return True

        self.ax.figure.canvas.draw()
        self.canvas.restore_region(self.background)

        self.lineRaw.set_data(self.xRaw, self.yRaw)
        self.ax.draw_artist(self.lineRaw)

        self.canvas.blit(self.ax.bbox)

data = defaultdict(list)
for i in range(100):
    data['polaris_rawPositions'].append(randn(200,2))

root = Tk.Tk()
root.wm_title("Data Explorer")

f = Figure()
ax = f.add_subplot(111)

canvas = FigureCanvasTkAgg(f, master=root)
canvas.get_tk_widget().pack(side=Tk.TOP, fill=Tk.BOTH, expand=1)
canvas.show()

Plotter = DataPlotter(ax, data)

spinbox = Tk.Spinbox(master=root, textvariable = Plotter.TrialNum, command = Plotter.updateDataToPlot, fg= 'black', from_ = 0, to = 100, increment = 1)
spinbox.pack(side=Tk.BOTTOM, anchor='e', padx = 5)

root.mainloop()

1 个答案:

答案 0 :(得分:0)

我在这里测试了tk.spinbox并且完美地作为你的布局工作,只是检查了你的代码是不是你得到任何异常?

#self.data = '/data/data', is this right?
#'/data/data'['polaris_rawPositions']
#also [:,0] using period, should use dots [:.0]
self.xRaw = self.data['polaris_rawPositions'][trialNum][:,0]

同样对于调试porpuse尝试在那里放一个打印,所以你可以检查值

trialNum = self.TrialNum.get()
print(trialNum)
抱歉,如果我遗漏了什么,我真的没碰到过matplotlib模块。