Pygame - rect 在我到达之前消失了 [英] Pygame - rect disappears before I reach it

查看:33
本文介绍了Pygame - rect 在我到达之前消失了的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在按下中键时弹出一个矩形,并保持弹出直到我在 pygame 中按下左键单击.

I am trying to make a rectangle pop up when middle click is pressed, and stay popped up until I press left click in pygame.

这是我的代码:

button1, button2, button3 = pygame.mouse.get_pressed()
if button2 == True:
    pygame.draw.rect(screen, ((255, 0, 0)), (0, int(h/2), int(w/6), int(h/2)-40), 0)
pygame.display.update()

问题是,当我按中键时,矩形出现,然后立即消失.我试过把它写成 while button2 == 2:,但程序挂了.

The thing is, when I press middle click, the rectangle appears, then disappears instantly. I have tried putting it as while button2 == 2:, but the program hangs.

谢谢!!

推荐答案

既然你想对不同的鼠标按钮点击做出反应,最好听听MOUSEBUTTONUP(或MOUSEBUTTONDOWN) 事件而不是使用 pygame.mouse.get_pressed().

Since you want to react to different mousebutton clicks, it's better to listen for the MOUSEBUTTONUP (or MOUSEBUTTONDOWN) events instead of using pygame.mouse.get_pressed().

您希望在按下鼠标按钮时更改应用程序的状态,因此您必须跟踪该状态.在这种情况下,一个变量就可以了.

You want to change the state of your application when a mousebutton is pressed, so you have to keep track of that state. In this case, a single variable will do.

这是一个最小的完整示例:

Here's a minimal complete example:

import pygame, sys
pygame.init()
screen = pygame.display.set_mode((300, 300))
draw_rect = False
rect = pygame.rect.Rect((100, 100, 50, 50))
while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            sys.exit()
        if e.type == pygame.MOUSEBUTTONUP:
            if e.button == 2:
                draw_rect = True
            elif e.button == 1:
                draw_rect = False

    screen.fill((255, 255, 255))
    if draw_rect:
        pygame.draw.rect(screen, (0, 0, 0), rect, 2)

    pygame.display.flip()

这篇关于Pygame - rect 在我到达之前消失了的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆