【问题标题】:Pygame - rect disappears before I reach itPygame - rect 在我到达它之前就消失了
【发布时间】:2023-03-15 04:42:01
【问题描述】:

我试图在按下中键时弹出一个矩形,并保持弹出状态,直到我在 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:,但是程序挂了。

谢谢!!

【问题讨论】:

  • 代码太短我看不懂。如果你能扩展你的代码就好了
  • 你是对的。我应该。我将发布一个新问题。
  • 更详细的问题是here

标签: python python-2.7 pygame


【解决方案1】:

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

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

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

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()

【讨论】:

    【解决方案2】:

    改变

    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()
    

    button1, button2, button3 = pygame.mouse.get_pressed()
    if button2 == True:
          rect_blit=True
    pygame.display.update()
    

    然后有

    if rect_blit==True:
        pygame.draw.rect(screen, ((255, 0, 0)), (0, int(h/2), int(w/6), int(h/2)-40), 0)
    

    在你的主循环中的某个地方(pygame.display.update 之前)。

    另一件事是你不需要说if some_variable == True:。相反,你可以说if some_variable:。他们做同样的事情。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多