在Python中作为全局时间连续更新定时器中断

时间:2017-05-09 23:41:46

标签: python user-interface slider interactive

我试图将名为' perpetualTimer'的定时器中断类导入文件ChangingPlot,并且我遇到了麻烦。本质上,此代码允许用户使用滑块在屏幕上移动蓝色标记并尝试跟随图形(在这种情况下,我使用对数图)。标记的y坐标由GUI slider widget控制,我希望x坐标由我在时间类中定义的连续时间步长控制。 ChangingPlot中的更新功能更新了这两个值,这是我不断导入和更新时间的麻烦。有人可以帮忙吗?

代码:

import matplotlib.pyplot as plt
import numpy as np
from timer import time
from matplotlib.widgets import Slider

from timer import time
from threading import Timer,Thread,Event

class perpetualTimer():

   def __init__(self,t,hFunction):
      self.t=t
      self.hFunction = hFunction
      self.thread = Timer(self.t,self.handle_function)

   def handle_function(self):
      self.hFunction()
      self.thread = Timer(self.t,self.handle_function)
      self.thread.start()

   def start(self):
      self.thread.start()

   def cancel(self):
      self.thread.cancel()

def timerloop():
   vec = np.arange(0,5,0.01) #time with time step
   for val in np.nditer(vec): 

      if val != 5:
         #print val
         return val

t = perpetualTimer(1,timerloop)
t.start()


class ChangingPlot(object):
    def __init__(self):
        #timestep value
        self.inc = 0.01

        self.fig, self.ax = plt.subplots()

         #[0.2, 0.02, 0.6, 0.03] define the position of the slider
        self.sliderax = self.fig.add_axes([0.2, 0.02, 0.6, 0.03], axisbg='yellow')

        #self.slider = Slider(self.sliderax, 'Value', 0, 10, valinit=self.inc)

        #max to initial value on the slide defined here and increment step is given by self.inc
        self.slider = Slider(self.sliderax, 'Value', 0, 10, valinit=self.inc)
        self.slider.on_changed(self.update)
        x = np.arange(0, 10.5,0.1) #gives the exact increments for the plot dots 
        #can define shape of base graph here
        self.ax.plot(x, 1/x, 'ro') #log graph coordinates
        self.dot, = self.ax.plot(2, 10, 'bo', markersize=18)


    def update(self, value):

        #link to value from slider 
        valuey = int(value / self.inc) * self.inc
        valuex = perpetualTimer(1,timerloop)

        self.dot.set_data([valuex],[valuey])
        self.slider.valtext.set_text('{}'.format(value))
        self.fig.canvas.draw()

    def show(self):
        plt.show()

p = ChangingPlot()
p.show() 

0 个答案:

没有答案