如何在线程Tkinter接口中创建散点图?

时间:2018-06-09 07:11:11

标签: python python-2.7 matplotlib tkinter scatter-plot

我有一个物体(来自V-Rep的机器人),我可以用get_pos()方法取得它的位置。我可以在带有散射函数的实时matplotlib图上绘制它并且效果很好:

while True:
n = 1000  # max number of points on plot
for i in range(0, n):
    point = get_pos()
    x = point[0]
    y = point[1]
    plt.scatter(x, y, s=5, c='r')
    plt.pause(0.01)
plt.show()

但现在我需要在我的Tkinter界面(单独的线程)中分散这个实时图。我是这样做的:

import Tkinter as Tk
from threading import Thread
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure


class Interface(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.tk = Tk.Tk()
        self.tk.title("Try to access")
        self.fig = Figure(figsize=(5, 4), dpi=100)
        self.plot = self.fig.add_subplot(111)
        self.canvas = FigureCanvasTkAgg(self.fig, master=self.tk)
        self.canvas.get_tk_widget().pack()
        self.canvas.draw()

    def add_point(self, x, y):
        self.plot.scatter(x, y, color='red')
        self.canvas.draw()

    def finish(self):
        self.tk.mainloop()


interface = Interface()
interface.start()

for i in xrange(0, 20):
    point = get_pos()  #get_pos() gets position of my robot (a tuple of 2 doubles)
    x = point[0]
    y = point[1]
    interface.add_point(x, y)
interface.finish()
interface.join()

我在界面中得到了什么 plot。 因此,它进行了所有20次迭代,然后绘制它,但我需要实时绘图。我做错了什么?

0 个答案:

没有答案