python 如何从pygame窗口中删除绘图对象?

qcbq4gxm  于 2023-04-19  发布在  Python
关注(0)|答案(3)|浏览(330)

我正在使用pygame和python创建一个游戏。我在窗口中绘制了一个矩形,它充当按钮。但我需要知道如何在单击按钮后删除按钮。以下是我的代码:

import pygame, sys
from pygame.locals import *
x = 0
y = 0

#Basic stuff:
pygame.init()
screen=pygame.display.set_mode((640,360),0,32)
pygame.display.set_caption("Some random Title")

while True:
    evc = pygame.event.get()
    for event in evc:
        if event.type == pygame.QUIT:
        pygame.quit()
        sys.exit()
x,y = pygame.mouse.get_pos()
screen.lock()
#draw button:
my_rect = pygame.draw.rect(screen,(205,201,201),Rect((245,40),(130,80)))
bf1 = pygame.font.SysFont("monospace", 15)
bl = bf1.render("Play!!!", 1, (255, 255, 255))
screen.unlock()
#Check mouse click!!!
if my_rect.collidepoint(x,y):
   for event in evc:
       if event.type ==pygame.MOUSEBUTTONUP:
           screen.fill((255,255,255))


screen.blit(bl, (280, 70))
pygame.display.flip
pygame.display.update()

所以是的我希望你能帮助我。

dphi5xsq

dphi5xsq1#

您需要将所有内容重新绘制到屏幕上,除了您不想再添加的部分。

pygame.init()
screen = pygame.display.set_mode((700, 700))
# set background or fill
background = pygame.image.load("/background.png")
screen.blit(background, (0, 0))    

my_btn = pygame.image.load("/button.png")
btn_rect = my_btn.get_rect()
screen.blit(my_btn, (0, 0))

for evt in pygame.event.get():

    if evt.type == pygame.MOUSEBUTTONDOWN:
        pos = pygame.mouse.get_pos()
        if btn_rect.collidepoint(pos):
            # do stuff
            # apply your background fill or image
            screen.blit(background, (0, 0))
            for element in elements_you_want_on_screen:
                screen.blit(element, (location))
    pygame.display.flip()

如果没有要进行位块传输的曲面阵列:

pygame.init()
screen = pygame.display.set_mode((700, 700))
# set background or fill
background = pygame.image.load("/background.png")
screen.blit(background, (0, 0))    

my_btn = pygame.image.load("/button.png")
btn_rect = my_btn.get_rect()
screen.blit(my_btn, (0, 0))

for evt in pygame.event.get():

    if evt.type == pygame.MOUSEBUTTONDOWN:
        pos = pygame.mouse.get_pos()
        if btn_rect.collidepoint(pos):
            # do stuff
            # apply your background fill or image
            screen.blit(background, (0, 0))
            screen.blit(your_image, (location))
            # ...and others if you have them
    pygame.display.flip()
cbeh67ev

cbeh67ev2#

我想你应该只为每一帧创建一个空白屏幕,然后把所有的东西都重新画一遍...

def draw(self):
self.screen.fill(self.color) #clear screen
self.draw(self.screen) # draw updated screen

如果你的代码中有不同的类,试着把那部分也加进去:

self.#class#.draw(self.screen)
but5z9lq

but5z9lq3#

我刚刚发现,但你也可以设置你的矩形的宽度和高度为0,并再次绘制它。在我看来,是更容易的方式。

相关问题