单击并拖动带有pygame的矩形

时间:2016-12-26 14:49:25

标签: python pygame

我是pygame的新手,我正在编写一个程序,允许用户在pygame窗口周围单击并拖动一个矩形,然后通过套接字发送它的坐标。我可以在鼠标点击时移动矩形,但我已经搞乱了一段时间,仍然无法弄清楚如何实现点击和拖动。任何帮助,将不胜感激。这是相关的代码:

Sum of Count    Column Labels                                               
Row Labels  15-Dec-16   16-Dec-16   17-Dec-16   18-Dec-16   19-Dec-16   20-Dec-16   21-Dec-16   22-Dec-16   23-Dec-16   24-Dec-16   25-Dec-16   26-Dec-16   Grand Total
ALTER                   1   1   2       1   3   8   791 807
Create                          135 92  61              288
Delete              1                           1   305 307
Insert                  1                           241 242
Modify  4   55  47  89  85  130 337 270 373 766 3012    1743    6911
Grand Total 4   55  47  90  87  131 474 362 435 769 3021    3080    8555

1 个答案:

答案 0 :(得分:7)

你必须使用

  • MOUSEBUTTONDOWN检查对象是否被点击并设置drag = True(并记住鼠标位置和矩形左上角之间的偏移量)
  • MOUSEBUTTONUP设置drag = False
  • MOUSEMOTION使用鼠标位置和偏移量drag == True时移动对象。

工作示例

import pygame

# --- constants --- (UPPER_CASE names)

SCREEN_WIDTH = 430
SCREEN_HEIGHT = 410

#BLACK = (  0,   0,   0)
WHITE = (255, 255, 255)
RED   = (255,   0,   0)

FPS = 30

# --- classses --- (CamelCase names)

# empty

# --- functions --- (lower_case names)

# empty

# --- main ---

# - init -

pygame.init()

screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
#screen_rect = screen.get_rect()

pygame.display.set_caption("Tracking System")

# - objects -

rectangle = pygame.rect.Rect(176, 134, 17, 17)
rectangle_draging = False

# - mainloop -

clock = pygame.time.Clock()

running = True

while running:

    # - events -

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:            
                if rectangle.collidepoint(event.pos):
                    rectangle_draging = True
                    mouse_x, mouse_y = event.pos
                    offset_x = rectangle.x - mouse_x
                    offset_y = rectangle.y - mouse_y

        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:            
                rectangle_draging = False

        elif event.type == pygame.MOUSEMOTION:
            if rectangle_draging:
                mouse_x, mouse_y = event.pos
                rectangle.x = mouse_x + offset_x
                rectangle.y = mouse_y + offset_y

    # - updates (without draws) -

    # empty

    # - draws (without updates) -

    screen.fill(WHITE)

    pygame.draw.rect(screen, RED, rectangle)

    pygame.display.flip()

    # - constant game speed / FPS -

    clock.tick(FPS)

# - end -

pygame.quit()

编辑: GitHub上有许多矩形或圆圈和按钮的其他示例:

furas/python-examples/pygame/drag-rectangles-circles