使用pygames模拟拖动选项

时间:2014-10-07 19:08:46

标签: python pygame

我想知道如何继续打印'测试'只有当我的鼠标左键被点击并且正在移动时?我试图模拟一种拖动选项。这就是我想出的:

导入pygame,sys 来自pygame.locals import *

pygame.init()
screen = pygame.display.set_mode((400, 300))
pygame.display.set_caption('Hello World!')
screen.fill((250, 250, 250))
x = 10
y = 10
pygame.draw.rect(screen, (0,0,0), (x,y, 100,100))
while True: # main game loop
     for event in pygame.event.get():
         if event.type == QUIT:
             pygame.quit()
             sys.exit()
         if event.type == MOUSEBUTTONDOWN: 
             if event.type == MOUSEMOTION: # This does not work
                 print 'test'
     pygame.display.update()

感谢您提供任何帮助或提示!

2 个答案:

答案 0 :(得分:2)

event.type一次只能是一件事,所以event.type == MOUSEBUTTONDOWN and event.type == MOUSEMOTION永远不会成真。

我要做的是创建一个按下鼠标按钮时为true的bool

mousebeingpressed = False
While True:
    for event in pygame.event.get():
        if event.type == MOUSEBUTTONDOWN:
            mousebeingpressed = True
        if event.type == MOUSEBUTTONUP:
            mousebeingpressed = False
        if event.type == MOUSEMOTION and mousebeingpressed == True:
            #do stuff

答案 1 :(得分:1)

最简单的方法是调用pygame.mouse.get_pressed()来检查是否按下鼠标按钮

for event in pygame.event.get():
     if event.type == MOUSEMOTION and pygame.mouse.get_pressed()[0]: 
         # do something

所以您不需要检查MOUSEBUTTONDOWN / MOUSEBUTTONUP,而且您不需要额外的变量。