简体   繁体   中英

python pyglet on_mouse_press

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()

在此处输入图片说明

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().

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM