如果在框中按下光标但未按下然后拖入光标,我该如何返回true?

时间:2017-02-17 07:52:06

标签: python-3.x pygame mouseevent

我在pygame中有一个框,如果在光标位于框内时按下鼠标按钮,我想将一些文本打印到控制台。问题是,如果按下鼠标按钮然后将其拖入框中,我就不希望打印文本。

我试过了:

if mousePos[0] >= 500 and mousePos[0] <= 530 and mousePos[1] >= 0 and mousePos[1] <= 100 and pygame.mouse.get_pressed()[0]:
    scrollButtonColour = (25,25,25)
    print(mousePos)
else:
    scrollButtonColour = (50,50,50)

干杯。

编辑:

以下是测试的完整代码(自发布问题后我做了一些细微更改):

import pygame

pygame.init()

white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)

display_width = 800
display_height = 600

gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Scroll Bar")
clock = pygame.time.Clock()

FPS = 60

gameExit = False

scrollButtonColour = (50,50,50)


while not gameExit:

    mousePos = pygame.mouse.get_pos()
    scrollButtonColour = (50,50,50)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True


    if mousePos[0] >= 500 and mousePos[0] <= 530 and mousePos[1] >= 0 and mousePos[1] <= 100:
        if pygame.mouse.get_pressed()[0]:
            scrollButtonColour = (25,25,25)
            print(mousePos)




    gameDisplay.fill(green)

    pygame.draw.rect(gameDisplay, red, (200,200,100,100))
    pygame.draw.rect(gameDisplay, scrollButtonColour, (500, 0, 30, 100))

    pygame.display.update()
    clock.tick(FPS)


pygame.quit()

2 个答案:

答案 0 :(得分:1)

确保仅在玩家点击内部时才打印事件 在播放器将鼠标拖入对象后,框并且不释放鼠标 你可以使用pygame.MOUSEBUTTONDOWN

这样您就可以检查鼠标是否实际按下了。如果你之后这样做 你已经检查过你的鼠标位置在对象内部,拖入了 不会打印对象,只会在对象内部单击。

这就是代码的样子:

if mousePos[0] >= 500 and mousePos[0] <= 530 and mousePos[1] >= 0 and mousePos[1] <= 100:
        if event.type == pygame.MOUSEBUTTONDOWN :
            scrollButtonColour = (25,25,25)
            print(mousePos)

要使此代码正常工作,您必须将此代码放入检查事件的循环中

答案 1 :(得分:0)

我首先检查是否按下了鼠标按钮,然后如果按钮rect与鼠标位置发生碰撞,请更改按钮的颜色并打印文本。释放按钮后,您可以重置颜色。我有一个例子,它还向您展示了如何使用pygame.Rect及其collidepoint方法。由于鼠标事件具有pos属性,因此您可以使用此属性而不是调用pygame.mouse.get_pos()

import sys
import pygame


pygame.init()

gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()

# Rect(x_pos, y_pos, width, height)
scrollButton = pygame.Rect(500, 0, 30, 100)
scrollButtonColour = (50, 50, 50)

gameExit = False

while not gameExit:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            gameExit = True
        if event.type == pygame.MOUSEBUTTONDOWN:
            if scrollButton.collidepoint(event.pos):
                scrollButtonColour = (25, 25, 25)
                print(event.pos)
        if event.type == pygame.MOUSEBUTTONUP:
            scrollButtonColour = (50, 50, 50)

    gameDisplay.fill((0, 255, 0))
    pygame.draw.rect(gameDisplay, scrollButtonColour, scrollButton)

    pygame.display.update()
    clock.tick(60)

pygame.quit()
sys.exit()

如果您想制作更多按钮或其他GUI元素,最好为它们定义类。将实例放入列表或sprite组,并在事件循环中将事件传递给实例以处理它们。