wxPython using wxTimer : my box doesn't move
I would like to animate a blue box inside a panel, using a wxTimer. But nothing happens
- I set up a custom panel class in which i draw the box
- I set up a custom frame, which integrates my custom panel
Here my code :
#!/usr/bin/python
# -*- coding: iso-8859-15 -*-
import wx
WHITE_COLOR = (255,255,255)
class AnimationPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.boxParameters = [10,10,60,60]
self.SetBackgroundColour(wx.Colour(*WHITE_COLOR))
self.Bind(wx.EVT_PAINT, self.OnPaint)
timer = wx.Timer(self)
timer.Start(100)
开发者_C百科 self.Bind(wx.EVT_TIMER, self.OnTimer, timer)
def OnPaint(self, event):
dc = wx.PaintDC(self)
self.paintBox(dc)
def OnTimer(self, event):
self.boxParameters[0] += 3
self.Update()
def paintBox(self, dc):
dc.SetBrush(wx.Brush("blue"))
dc.DrawRectangle(*self.boxParameters)
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Box with far and back movement", size=(300,200))
AnimationPanel(self)
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MainFrame()
frame.Show(True)
app.MainLoop()
Thanks in advance
You are missing a couple of things. First is that the wx.Timer is going out of scope once you've reached the end of the init method, so it's destroyed before it even gets to do anything. Next, you want to use Refresh() instead of Update() as Refresh() will mark the rectangle (or the entire screen) as "dirty" and cause it to be repainted. See the docs for more info: http://www.wxpython.org/docs/api/wx.Window-class.html
Here's an updated version that works on my Windows box:
import wx
WHITE_COLOR = (255,255,255)
class AnimationPanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.boxParameters = [10,10,60,60]
self.SetBackgroundColour(wx.Colour(*WHITE_COLOR))
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.timer = wx.Timer(self)
self.Bind(wx.EVT_TIMER, self.OnTimer, self.timer)
self.timer.Start(100)
def OnPaint(self, event):
dc = wx.PaintDC(self)
self.paintBox(dc)
def OnTimer(self, event):
self.boxParameters[0] += 3
print self.boxParameters
self.Refresh()
def paintBox(self, dc):
dc.SetBrush(wx.Brush("blue"))
dc.DrawRectangle(*self.boxParameters)
class MainFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, title="Box with far and back movement", size=(300,200))
AnimationPanel(self)
if __name__ == "__main__":
app = wx.PySimpleApp()
frame = MainFrame()
frame.Show(True)
app.MainLoop()
精彩评论