Skip to main content
 首页 » 编程设计

python之如何删除由 pygbutton 创建的按钮

2024年10月25日11kerrycode

我想删除由 PygButton 创建的按钮.我是这样创建的:

button1 = pygbutton.PygButton((50, 50, 60, 30), '1') 
button2 = pygbutton.PygButton((120, 50, 60, 30), '2') 
button3 = pygbutton.PygButton((190, 50, 60, 30), '3') 
allButtons = (button1,button2,button3) 
 
for b in allButtons: 
    b.draw(screen) 

但是,一旦单击按钮,我想清除屏幕中的按钮并在屏幕上显示其他内容。

我该怎么做?

请您参考如下方法:

我想到的一般想法是在按下按钮后创建一个新屏幕。

基本上,我有一个名为 buttonhasbeenpressed 的 bool 值。在按下按钮之前,我们只是检查 event 是否是按下按钮。在它被按下后,我们将 bool 设置为 True,“清除”背景(通过在旧屏幕上创建一个新屏幕),然后继续做我们想做的任何其他事情。我的示例代码仅“删除”按钮、更改背景颜色和更改窗口上的标题,但您可以使用此想法来更改您想要的有关按下按钮后游戏状态的任何内容。

这是示例,您应该能够在您的机器上运行以进行测试。

import pygame,pygbutton 
from pygame.locals import * 
pygame.init() 
 
#Create the "Pre Button Press Screen" 
width = 1024 
height = 768 
screen = pygame.display.set_mode([width,height]) 
pygame.display.set_caption('OLD SCREEN NAME') 
background = pygame.Surface(screen.get_size()) 
background = background.convert() 
background.fill((250, 250, 250)) 
screen.blit(background, [0,0]) 
pygame.display.flip() 
button1 = pygbutton.PygButton((50, 50, 60, 30), '1') 
button2 = pygbutton.PygButton((120, 50, 60, 30), '2') 
button3 = pygbutton.PygButton((190, 50, 60, 30), '3') 
buttonhasbeenpressed = False 
 
def screenPostButtonPress(): 
    width = 1024 
    height = 768 
    screen = pygame.display.set_mode([width,height]) 
    pygame.display.set_caption('NEW SCREEN NAME!!!!!!!') 
    background = pygame.Surface(screen.get_size()) 
    background = background.convert() 
    background.fill((20, 20, 40)) 
    screen.blit(background, [0,0]) 
    pygame.display.flip() 
    #buttons not on screen after a button has been pressed 
 
def waitingForButtonClick(): 
    allButtons = [button1,button2,button3]         
    buttonevent1 = button1.handleEvent(event) 
    buttonevent2 = button2.handleEvent(event) 
    buttonevent3 = button3.handleEvent(event) 
 
    for b in allButtons: 
        b.draw(screen) 
 
    if 'click' in buttonevent1 or 'click' in buttonevent2 or 'click' in buttonevent3: 
        return False 
    return True 
 
while True: 
    for event in pygame.event.get(): 
        if event.type == QUIT: 
            pygame.quit() 
            sys.exit() 
    #Wait for a button to be pressed, once one has, "clear" the screen by creating a new screen 
    if buttonhasbeenpressed == False and waitingForButtonClick() == False: 
       buttonhasbeenpressed = True 
       screenPostButtonPress() 
    pygame.display.update()