My main purpose is to draw a line on ShapeCanvas when when clicking the Add Edge button. The code I wrote is below:
import wx
import wx.lib.ogl as ogl
class MyPen:
def __init__(self, color, width, style):
self.my_pen = wx.Pen()
wx.Pen.SetColour(self.my_pen, color)
wx.Pen.SetWidth(self.my_pen, width)
wx.Pen.SetStyle(self.my_pen, style)
class EdgeShape(ogl.LineShape):
def __init__(self, arrow, x1, y1, x2, y2, selected, canvas):
super().__init__()
if arrow:
self.AddArrow(ogl.ARROW_ARROW)
self.MakeLineControlPoints(2)
self.SetEnds(x1, y1, x2, y2)
self.pen = MyPen(wx.Colour(0, 0, 0), 2, wx.PENSTYLE_SOLID).my_pen
self.brush = wx.BLACK_BRUSH
self.SetPen(self.pen)
self.SetBrush(self.brush)
self.SetCanvas(canvas)
canvas.diagram.AddShape(self)
self.Show(True)
class GraphCanvas(ogl.ShapeCanvas):
def __init__(self, parent):
# def __init__(self, parent, shape):
super().__init__(parent)
maxWidth = 1000
maxHeight = 1000
self.SetScrollbars(20, 20, maxWidth // 20, maxHeight // 20)
self.SetBackgroundColour("LIGHT BLUE")
# Create a diagram and assign the diagram to the ShapeCanvas and assign the ShapeCanvas to the diagram
self.diagram = ogl.Diagram()
self.SetDiagram(self.diagram)
self.diagram.SetCanvas(self)
class MyFrame(wx.Frame):
def __init__(self):
super().__init__(None, title="wxPython OGL Clickable Shapes")
add_edge_btn = wx.Button(self, label="Add Edge")
add_node_btn = wx.Button(self, label="Add Node")
# Setup and display the ShapeCanvas
self.graph_canvas = GraphCanvas(self)
main_sizer = wx.BoxSizer(wx.HORIZONTAL)
button_sizer = wx.BoxSizer(wx.VERTICAL)
button_sizer.Add(add_edge_btn, flag=wx.CENTER)
button_sizer.Add(add_node_btn, flag=wx.CENTER)
main_sizer.Add(button_sizer, proportion=1, flag=wx.EXPAND)
main_sizer.Add(self.graph_canvas, proportion=3, flag=wx.EXPAND)
self.SetSizer(main_sizer)
add_edge_btn.Bind(wx.EVT_BUTTON, self.add_edge)
add_node_btn.Bind(wx.EVT_BUTTON, self.add_node)
# edge_shape = EdgeShape(False, 10, 10, 100, 100, False, self.graph_canvas)
self.Show()
def add_edge(self, event):
edge_shape = EdgeShape(False, 10, 10, 100, 100, False, self.graph_canvas)
def add_node(self, event):
pass
if __name__ == '__main__':
app = wx.App(False)
ogl.OGLInitialize()
frame = MyFrame()
app.MainLoop()
The code above does not initially shows the line. However, the line is shown only after I use the scroll bars. The intent is to have the line shown immediately after pressing the button.
I tried moving this line
edge_shape = EdgeShape(False, 10, 10, 100, 100, False, self.graph_canvas)
to be under MyFrame class instead of under the add_edge() event and the line shows up immediately.
Can someone please help me to know whey the line does not display when it is created under the even function? Thanks