Question

I'm trying to make a simple GUI using pyglet.

Here is my code:

button_texture = pyglet.image.load('button.png')
button = pyglet.sprite.Sprite(button_texture, x=135, y=window.height-65)

def on_mouse_press(x, y, button, modifiers):
   if x > button and x < (button + button_texture.width):
      if y > button and y < (button + button_texture.height):
         run_program()

enter image description here

The problem

The "button.png" is displayed as the red box with "Click" inside. and is supposed to start run_program(). But currently the yellow in the bottom left is the place i have to click to initiate run_program().

Was it helpful?

Solution

You are comparing the button (the key-code) with the X/Y coordinates. This happens, because the function parameter button shadows your global variable. Also, you should use the buttons x, y, width and height attributes.

button_texture = pyglet.image.load('button.png')
button_sprite = pyglet.sprite.Sprite(button_texture, x=135, y=window.height-65)

def on_mouse_press(x, y, button, modifiers):
   if x > button_sprite.x and x < (button_sprite.x + button_sprite.width):
      if y > button_sprite.y and y < (button_sprite.y + button_sprite.height):
         run_program()

I renamed your global variable button with button_sprite to avoid the name collision.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top