How can I detect if the user has double-clicked in pygame?

后端 未结 5 1479
夕颜
夕颜 2020-12-06 07:34

I know I can check if there was a left click

event.type == pygame.MOUSEBUTTONDOWN and event.button == LEFT

but how can I check if they doub

5条回答
  •  隐瞒了意图╮
    2020-12-06 07:59

    A very simple solution is to define a pygame.time.Clock() to keep track of the time between two consecutive MOUSEBUTTONDOWN event.

    Before the main loop define:

    dbclock = pygame.time.Clock()
    

    and in the event loop controller:

    if event.type == pygame.MOUSEBUTTONDOWN:
        if dbclock.tick() < DOUBLECLICKTIME:
            print("double click detected!")
    

    where DOUBLECLICKTIME is the maximum time allowed (in milliseconds) between two clicks for them being considered a double click. Define it before the mainloop. For example, to allow a maximum delay of half a second between the two clicks: DOUBLECLICKTIME = 500.

    In pygame is possible to create as many pygame.time.Clock() objects are needed. dbclock must be used only for this purpose (I mean, no other calls to dbclock.tick() anywhere in the main loop) or it will mess with the tracking of the time between the two clicks.


    For the sake of completeness, let me add also the answer about the scroll wheel, even if other answers already covered it.
    The scroll wheel emits MOUSEBUTTONDOWN and MOUSEBUTTONUP events (it's considered a button). I can be identified by the event.button parameter, which is 4 when the wheel is rolled up, and 5 when the wheel is rolled down.

提交回复
热议问题