【发布时间】:2025-12-24 09:15:11
【问题描述】:
我正在尝试编写一个 python 代码,它在 for 循环中创建和初始化 n 计时器并将它们绑定到一些事件。下面的代码是我这样做的一个例子:
import wx
#dm1 = {a dewell times values dictionary}
#screens = [a list of dm1 keys]
trials = range(1, 3)
timers = range(0, 4)
class DM1(wx.Frame):
def __init__(self, *args, **kwargs):
wx.Frame.__init__(self, *args, **kwargs)
panel = wx.Panel(self)
self.Go = wx.Button(panel, label = 'Go!', pos = (600, 450))
self.Bind(wx.EVT_BUTTON, self.BuildTimers, self.Go)
def BuildTimers(self, event):
self.timers = {}
cum_timer = 0
for trial in trials:
for timer in timers:
key = (timer, trial)
new_timer = wx.Timer(self)
cum_timer += dm1[screens[timer]]
new_timer.Start(cum_timer * 1000, False)
new_timer.mykey = key
self.timers[key] = new_timer
self.Bind(wx.EVT_TIMER, self.Screens)
def Screens(self, event):
if event.GetEventObject() == self.timers[event.GetEventObject().mykey]:
print event.GetEventObject().mykey
if event.GetEventObject().mykey[0] == 0:
print 'You bastard!'
if event.GetEventObject().mykey[0] == 1:
print 'you vicious...'
if event.GetEventObject().mykey[0] == 2:
print 'heartless bastard!'
if event.GetEventObject().mykey[0] == 3:
print 'Oh It makes me mad!'
app = wx.App()
frame = DM1(None, title = 'IG', size = (wx.DisplaySize()))
frame.Show()
app.MainLoop()
计时器在我指定的时间没有启动:trial 的第二个循环似乎覆盖了第一个循环。例如,语句print event.GetEventObject().mykey,在完整的代码中,打印出
(0, 1) (1, 1) (1, 2) (2, 1) (3, 1) (0, 2) (3, 1) (2, 1)
而不是
(0, 1) (1, 1) (2, 1) (3, 1) (0, 2) (1, 2) (2, 2) (3, 2)
我猜问题出在GetEventObject,但我不知道将计时器绑定到事件的更好方法。有人有想法吗?
非常感谢!
【问题讨论】:
标签: python events timer wxpython bind