Pygame:检查按钮是否被按下

时间:2017-08-03 15:13:14

标签: python pygame

我正在使用pygame在python的游戏的开始菜单上工作,我做了一个函数来检测鼠标是否按下了每个按钮的位置,如果是,它会改变一个布尔值的值来表示按钮。但是布尔值没有改变。

这是我的代码:

import pygame
import sys
import sqlite3 as lite

# questions
option_1 =  option_2 =  option_3 =  option_4 = ''

# misc
initial_pos = 220
event_i = False
event_g = False
event_t = False
event_e = False

...

# Button Settings
button = pygame.image.load("src/trans-button.png")
button = pygame.transform.scale(button, (display_width - 84, 70))

button_start = button_tutorial = button_top10 = button_salir = button

# Game Functions

def checkSelection():
    # We get the mouse coordinates
    mouse_x, mouse_y = pygame.mouse.get_pos()

    # Then proceed to evaluate it's position in relation with the buttons

    if(mouse_x >= 42 and mouse_x <= button.get_width() + 42 and mouse_y >= initial_pos and mouse_y <= initial_pos + button.get_height()):
        event_i = True
    if(mouse_x >= 42 and mouse_x <= button.get_width() + 42 and mouse_y >= initial_pos + button.get_height() + 25 and mouse_y <= initial_pos + button.get_height()*2 + 25):
        event_g = True
    if(mouse_x >= 42 and mouse_x <= button.get_width() + 42 and mouse_y >= initial_pos + button.get_height()*2 + 50 and mouse_y <= initial_pos + button.get_height()*3 + 50):
        event_t = True
    if(mouse_x >= 42 and mouse_x <= button.get_width() + 42 and mouse_y >= initial_pos + button.get_height()*3 + 75 and mouse_y <= initial_pos + button.get_height()*4 + 75):
        event_e = True

...

# Game Loop
while not crashed:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        if event.type == pygame.MOUSEBUTTONDOWN:
            checkSelection()
            checkSelection()

    if event_i:
        print 'Begin'
    if event_e:
        print 'It should exit'
        crashed = True

    window.blit(background, (0,0))
    drawAll()
    pygame.display.update()
    clock.tick(60)

#End Game
pygame.quit()
quit()
sys.exit()

'...'是我在代码中做的跳转,只显示与问题相关的部分。

位置检测确实有效,我使用'print'进行检查以进行重新布线。

- 更新 -

意外删除了定义按钮的部分 还有一些我在将代码恢复到原始状态时所做的拼写错误。

1 个答案:

答案 0 :(得分:3)

问题是checkSelection()函数中的变量是局部变量。您需要在函数中将变量声明为global

def checkSelection():
    global event_i
    global event_t
    # ...

Python中的局部变量和全局变量的规则在官方Python编程常见问题解答中很简单summarised

P.S。在函数内部使用全局变量不是一个好主意。我建议定义一个只检查一个按钮区域并返回结果的函数,该结果可以分配给(全局)变量:

def checkSelection(x, y):
    mouse_x, mouse_y = pygame.mouse.get_pos()
    return x <= mouse_x <= x + button.get_width() and
           y <= mouse_y <= y + button.get_height()

...
event_i = checkSelection(42, 25)
event_t = checkSelection(42, 50)
...