wxpython在for循环中启动多个计时器

时间:2012-06-15 19:56:24

标签: python loops timer wxpython

我想在for循环中创建和启动多个计时器。我的方法如下:

import wx

trials = range(1, 3)
timers = range(7)
name = 'timer'

class TimersClass(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

    panel = wx.Panel(self)
    self.button1 = wx.Button(panel, label = 'Go')
    self.Bind(wx.EVT_BUTTON, self.Timers, self.button1)

    def Timers(self, event):
        for trial in trials:
            for timer in timers:
                setattr(self, name + str(timer) + '_' + 'iteration' + str(trial), wx.Timer(self))
                print name + str(timer) + '_' + 'iteration' + str(trial)

                eval(name + str(timer) + '_' + 'iteration' + str(trial) + '.Start(' + str(timer * 1000, ) + ', OneShoot = True)')

        self.Bind(wx.EVT_TIMER, self.Hi)

    def Hi(self, event):
        print 'Hi, bastard!'


app = wx.App()
frame = TimersClass(None)
frame.Center()
frame.Show()

app.MainLoop()

但是self.timers对象似乎没有被创建:

追踪(最近一次通话):   在Timers中输入第24行“Escritorio / iteration_timers.py”     eval(name + str(timer)+'_'+'iteration'+ str(trial)+'。Start('+ str(timer * 1000,)+',OneShoot = True)')   文件“”,第1行,in NameError:名称'timer0_iteration1'未定义

有人知道为什么这段代码没有运行,或者有另一种方法?

非常感谢!!

1 个答案:

答案 0 :(得分:0)

我建议在类中使用合理的结构来存储定时器(而不是创建一堆具有复杂编码名称的类属性)。这是一个例子:

import wx

trial_range = range(1, 3)
timer_range = range(7)

class TimersClass(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        panel = wx.Panel(self)
        self.button1 = wx.Button(panel, label = 'Go')
        self.Bind(wx.EVT_BUTTON, self.BuildTimers, self.button1)

        self.timers = {}  # a structure to hold the timers

    def BuildTimers(self, event):
        for trial in trial_range:
            for timer in timer_range:
                new_timer = wx.Timer(self)
                new_timer.Start(1 + timer*1000, oneShot=True)

                key = (trial, timer)
                self.timers[key] = new_timer # to keep the timer in the class
                new_timer.mykey = key  #optional: to know the key of the timer via the event (see Hi())

        self.Bind(wx.EVT_TIMER, self.Hi)

    def Hi(self, event):
        print "timer:",
        print event.GetEventObject().mykey


app = wx.PySimpleApp() 
frame = TimersClass(None)
frame.Center()
frame.Show()
app.MainLoop()

当它运行时,它产生:

timer: (1, 0)
timer: (2, 0)
timer: (1, 1)
timer: (2, 1)
timer: (1, 2)
# etc