Hello everyone.
I’m new to wxPython and still learning it. I tried a sample code to draw some circles on a Diagram but the code is giving me an error which I could not really figure where it is coming from.
I compared this code against different sources, and it seems to me to be correct but I’m sure I’m missing something.
I appreciate if someone can help me figure this out.
Here is the code:
import wx
from wx.lib.ogl import *
# Create a class for the scrolled canvas
class MyScrolledCanvas(wx.ScrolledCanvas):
def __init__(self, parent):
wx.ScrolledCanvas.__init__(self, parent, style=wx.VSCROLL | wx.HSCROLL)
self.SetBackgroundColour(wx.WHITE)
# Set up a virtual size for the drawing area
self.SetVirtualSize((2000, 2000))
self.SetScrollRate(20, 20)
# Create the OGL canvas
self.ogl_canvas = ShapeCanvas(self)
self.ogl_canvas.SetBackgroundColour(wx.WHITE)
self.diagram = Diagram()
self.ogl_canvas.SetDiagram(self.diagram)
self.diagram.SetCanvas(self.ogl_canvas)
# Connect the Paint event
self.Bind(wx.EVT_PAINT, self.OnPaint)
self.create_shapes()
def create_shapes(self):
# Create some shapes to test scrolling
for i in range(5):
for j in range(5):
shape = CircleShape(50)
# shape = CircleShape(50)
shape.SetX(100 + i * 200)
shape.SetY(100 + j * 200)
self.diagram.AddShape(shape)
def OnPaint(self, event):
dc = wx.PaintDC(self)
self.PrepareDC(dc)
self.ogl_canvas.OnPaint(event) # Call the OGL canvas's paint method
class MyFrame(wx.Frame):
def __init__(self, parent, title):
wx.Frame.__init__(self, parent, title=title, size=(800, 600))
panel = wx.Panel(self)
sizer = wx.BoxSizer(wx.VERTICAL)
# Add the custom scrolled canvas to the sizer
scrolled_canvas = MyScrolledCanvas(panel)
sizer.Add(scrolled_canvas, 1, wx.EXPAND | wx.ALL, 5)
panel.SetSizer(sizer)
self.Layout()
if __name__ == '__main__':
app = wx.App(False)
frame = MyFrame(None, "Scrolled ShapeCanvas Example")
frame.Show()
app.MainLoop()
These are the errors that I’m getting:
Traceback (most recent call last):
File "main.py", line 59, in <module>
frame = MyFrame(None, "Scrolled ShapeCanvas Example")
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "main.py", line 50, in __init__
scrolled_canvas = MyScrolledCanvas(panel)
^^^^^^^^^^^^^^^^^^^^^^^
File "main.py", line 25, in __init__
self.create_shapes()
File "main.py", line 31, in create_shapes
shape = CircleShape(50)
^^^^^^^^^^^^^^^
File "venv\Lib\site-packages\wx\lib\ogl\basic.py", line 3541, in __init__
EllipseShape.__init__(self, diameter, diameter)
File "venv\Lib\site-packages\wx\lib\ogl\basic.py", line 3381, in __init__
Shape.__init__(self)
File "venv\Lib\site-packages\wx\lib\ogl\basic.py", line 329, in __init__
self._pen = BlackForegroundPen
^^^^^^^^^^^^^^^^^^
NameError: name 'BlackForegroundPen' is not defined