Apara
Apara

Reputation: 374

How to draw a shape on an image in Pyglet upon mouse press?

I want to display an image in Pyglet. And then upon mouse click, I want to draw a shape (let's say a circle) to mark the clicked point on the image. This is what I have so far

window = pyglet.window.Window(width=1600, height=700)
gui = glooey.Gui(window)
hbox = glooey.HBox()

# Loading the image
image = pyglet.image.load("image.png")
img_widget = glooey.images.Image(image=image, responsive=True)
hbox.add(img_widget)

hbox.add(glooey.PlaceHolder())
gui.add(hbox)

# Mouse press events
@img_widget.event
def on_mouse_press(x, y, buttons, modifiers):
    # If left shift + left mouse button is pressed
    if modifiers == 1 and buttons == 1:
        circle = shapes.Circle(x=x, y=y, radius=10, color=(50, 225, 30))
        circle.draw()
        window.flip()
    return

pyglet.app.run()

When I click, having the line window.flip() makes the circle flicker. If I remove it, I don't see anything. How do I make these shapes persist? The goal is for me to click on several points in the image and have them all shown at the same time.

Thank you for the help!

Upvotes: 3

Views: 626

Answers (1)

Rabbid76
Rabbid76

Reputation: 210877

A a list to store the circels:

circles = []

Create a circle shape and set the batch argument (batch = batch=gui.batch). Append the shape to the list:

circle = shapes.Circle(x=x, y=y, radius=10, color=(50, 225, 30), batch=gui.batch)
circles.append(circle)

Complete example

import pyglet
from pyglet import shapes
import glooey

window = pyglet.window.Window(width=1600, height=700)
gui = glooey.Gui(window)
hbox = glooey.HBox()

# Loading the image
image = pyglet.image.load("image.png")
img_widget = glooey.images.Image(image=image, responsive=True)
hbox.add(img_widget)

hbox.add(glooey.PlaceHolder())
gui.add(hbox)

circles = []

# Mouse press events
@img_widget.event
def on_mouse_press(x, y, buttons, modifiers):
    # If left shift + left mouse button is pressed
    if modifiers == 1 and buttons == 1:
        circle = shapes.Circle(x=x, y=y, radius=10, color=(50, 225, 30), batch=gui.batch)
        circles.append(circle)

pyglet.app.run()

Upvotes: 2

Related Questions