2

I'm trying to create a square that forms around the drag of a mouse (like the one that appears when dragging on the desktop, for example.) THis is the code I've tried:

import pyglet
from pyglet.window import mouse

window = pyglet.window.Window()

@window.event
def on_draw():
    window.clear()

@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [x, y, dx, y, dx, dy, x, dy]))

pyglet.app.run()

However, it's not working, and I can't see why. Any advice?

3 Answers 3

6

So, as there hasn't been an answer, this is how I solved the problem:

import pyglet
from pyglet.window import mouse

window = pyglet.window.Window()

@window.event
def on_draw():
    pass

@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, ('v2f', [x, y, x-dx, y, x-dx, y-dy, x, y-dy]))
    print x, y, dx, y, dx, dy, x, dy
pyglet.app.run()

Now I just need to work out how to destroy the rectangles...

0
6

I started with your solution and improved it a bit. The rectangle artifacting problem is fixed by adding an on_draw function, and in that function you clear the window and then re-draw every object. Pyglet (OpenGL) uses double-buffering, so this works a lot faster than it sounds.

import pyglet

# rectangle class

class Rect:

  def __init__(self, x, y, w, h):
    self.set(x, y, w, h)

  def draw(self):
    pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, self._quad)

  def set(self, x=None, y=None, w=None, h=None):
    self._x = self._x if x is None else x
    self._y = self._y if y is None else y
    self._w = self._w if w is None else w
    self._h = self._h if h is None else h
    self._quad = ('v2f', (self._x, self._y,
                          self._x + self._w, self._y,
                          self._x + self._w, self._y + self._h,
                          self._x, self._y + self._h))

  def __repr__(self):
    return f"Rect(x={self._x}, y={self._y}, w={self._w}, h={self._h})"

# main function

def main():
  r1 = Rect(10, 10, 100, 100)
  window = pyglet.window.Window()

  @window.event
  def on_draw():
    window.clear()
    r1.draw()

  @window.event
  def on_mouse_press(x, y, button, modifiers):
    r1.set(x=x, y=y)
    print(r1)

  @window.event
  def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    r1.set(x=x, y=y)
    print(r1)

  pyglet.app.run()

if __name__ == '__main__':
  main()
2
  • When I run your script, I get: return f"Rect(x={self._x}, y={self._y}, w={self._w}, h={self._h})" SyntaxError: invalid syntax is this a python 2 vs python 3 thing? If I comment it, the script runs properly.
    – mm_
    Jul 3, 2018 at 3:00
  • 1
    Also, I don't understand how you are passing your class rectangle to the window. That is, how does pyglet.graphics.draw(4, pyglet.gl.GL_QUADS, self._quad) knows it has to draw the rectangle in window = pyglet.window.Window(). (Cus it's the active window?)
    – mm_
    Jul 3, 2018 at 3:02
0
import pyglet
from pyglet import shapes
from pyglet.shapes import BorderedRectangle
from pyglet.window import key

def init():
    display = pyglet.canvas.get_display()

    # for screen in display.get_screens():
    #     print(screen)

    screen = display.get_screens()[0]
    config = pyglet.gl.Config(double_buffer=True)

    return pyglet.window.Window(screen = screen, config=config, resizable=True)

window = init()
batch = pyglet.graphics.Batch()
box_list = []
drawing_box = False
rectangle = None
box_position = [0,0,0,0]
X = 0
Y = 1
W = 2
H = 3


def getSelected(x, y):
    pass

@window.event
def on_draw():
    window.clear()
    batch.draw()
    pyglet.gl.glFlush()

@window.event
def on_resize(width, height):
    print(f"window resized width: {width} and height: {height}")

@window.event
def on_key_press(symbol, modifiers):
    print(f"key: {chr(symbol)} pressed with modifier: {modifiers}")
    return True

@window.event
def on_key_release(symbol, modifiers):
    global drawing_box
    global rectangle

    #print(f"this keys: {chr(symbol)} and modifiers: {modifiers} are no longer pressed")
    if (drawing_box == True):
        drawing_box = False
        if box_position[W] < 0:
            box_position[X] = box_position[X] + box_position[W]
            box_position[W] = -box_position[W]

        if box_position[H] < 0:
            box_position[Y] = box_position[Y] + box_position[H]
            box_position[H] = -box_position[H]

        rectangle = shapes.BorderedRectangle(box_position[0], box_position[1], box_position[2], box_position[3],
                                             border=3, color=(200, 200, 200),
                                             border_color=(255, 255, 255), batch=batch)
        rectangle.opacity = 100
        box_list.append(rectangle)
        rectangle = None

@window.event
def on_mouse_press(x, y, button, modifiers):
    #print(f"button : {button} at ({x},{y}) modifiers: {modifiers}")
    global drawing_box
    global box_position

    if(modifiers == key.MOD_SHIFT):
        drawing_box = True
        box_position[0] = x
        box_position[1] = y
    else:
        selected = getSelected(x, y)

import inspect

@window.event
def on_mouse_drag(x, y, dx, dy, buttons, modifiers):
    #print(f"mouse dragging at x: {x}, y: {y} button: {buttons} and modifier: {modifiers} are pressed")
    global drawing_box
    global box_position
    global rectangle

    if drawing_box == True:
        box_position[2] = x-box_position[0]
        box_position[3] = y -box_position[1]
        rectangle = shapes.BorderedRectangle(box_position[0], box_position[1], box_position[2], box_position[3],
                                             border=3,color=(200,200,200),border_color=(255, 255, 255), batch=batch)
        rectangle.opacity = 100


if __name__ == "__main__":
    pyglet.app.run()




#attrs = vars(rectangle)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
#print(', '.join("%s: %s" % item for item in attrs.items()))
#print(inspect.getmembers(BorderedRectangle, predicate=inspect.isfunction))

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.