Hello,
I'd like to redraw some graphics at regular intervals for a dashboard
app, using OnTimer together with OnPaint. When running the example
code below, I get an error message "wxPaintDC may be created only in
EVT_PAINT handler!".
This is basically my first wxPython project - any help appreciated!
Thanks,
Kevin
import random
import wx
import time
# Using Ontimer and OnPaint together to redraw at scheduled intervals
# snippet modified from http://www.daniweb.com/code/snippet216648.html
class MyPanel(wx.Panel):
""" class MyPanel creates a panel to draw on, inherits wx.Panel """
def __init__(self, parent, id):
# create a panel
wx.Panel.__init__(self, parent, id)
self.SetBackgroundColour("white")
# start the paint event for DrawRectangle() and FloodFill()
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.timer = wx.Timer(self)
self.timer.Start(1000) # 1000 milliseconds = 1 second
self.Bind(wx.EVT_TIMER, self.OnTimer)
def OnTimer(self, evt):
self.draw_rectangle()
def OnPaint(self, evt):
self.draw_rectangle()
def draw_rectangle(self):
"""set up the device context (DC) for painting"""
self.dc = wx.PaintDC(self)
self.dc.Clear()
self.dc.BeginDrawing()
self.dc.SetPen(wx.Pen("BLACK",1))
# draw a random rectangle ...
# set random RGB color for brush
r = random.randrange(256)
g = random.randrange(256)
b = random.randrange(256)
self.dc.SetBrush(wx.Brush((r, g, b), wx.SOLID))
# set random x, y, w, h for rectangle
w = random.randint(10, width1/2)
h = random.randint(10, height1/2)
x = random.randint(0, width1 - w)
y = random.randint(0, height1 - h)
self.dc.DrawRectangle(x, y, w, h)
self.dc.EndDrawing()
# free up the device context now
del self.dc
height1 = 350
width1 = 400
app = wx.PySimpleApp()
# create a window/frame, no parent, -1 is default ID
frame = wx.Frame(None, -1, "Draw a rectangle using Timer ...", size =
(width1, height1))
# call the derived class, -1 is default ID
MyPanel(frame,-1)
# show the frame
frame.Show(True)
# start the event loop
app.MainLoop()