python pyglet on_mouse_press

人走茶凉 提交于 2020-01-24 23:55:12

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/21234381/python-pyglet-on-mouse-press

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!