I am working on a simple candlestick chart drawing program using Pyglet. When I try to batch shapes within a loop, pyglet only draws the first shape (I think). I have included some minimal code to explain my problem. This code should display 10 thin, long rectangles across the window, but I get just one rectangle.
import pyglet
from pyglet import shapes
window = pyglet.window.Window(960, 540)
batch = pyglet.graphics.Batch()
for i in range(10):
rectangle = shapes.Rectangle(10*i, 100, 5, 100, color=(0,255,0), batch=batch)
@window.event
def on_draw():
window.clear()
batch.draw()
pyglet.app.run()
print(batch)
Something like this works fine:
rectangle1 = shapes.Rectangle(10, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle2 = shapes.Rectangle(20, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle3 = shapes.Rectangle(30, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle4 = shapes.Rectangle(40, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle5 = shapes.Rectangle(50, 100, 5, 100, color=(0,255,0), batch=batch)
But this does not:
rectangle = shapes.Rectangle(10, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle = shapes.Rectangle(20, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle = shapes.Rectangle(30, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle = shapes.Rectangle(40, 100, 5, 100, color=(0,255,0), batch=batch)
rectangle = shapes.Rectangle(50, 100, 5, 100, color=(0,255,0), batch=batch)
This implies to me that the batch object just refers to the shape objects within the batch, which would make my plan of plotting graph data impossible with pyglet batches, am I correct in this assumption?
Thanks for any help
I recommend to add the shapes to a list:
rectangles = []
for i in range(10):
rectangles.append(shapes.Rectangle(10*i, 100, 5, 100, color=(0,255,0), batch=batch))
respectively
rectangles = [shapes.Rectangle(10*i, 100, 5, 100, color=(0,255,0), batch=batch) for i in range(10)]