#Importing Modules
import pygame as pg
import sys
import random
#All pygame stuff under here
pg.init()
#Font definitions
backFont = pg.font.SysFont("monospace",40)
titleFont = pg.font.SysFont("garamond", 100)
cipherFont = pg.font.SysFont("garamond", 50)
buttonFont = pg.font.SysFont("garamond", 25)
bigFont = pg.font.SysFont("garamond",100)
Font = pg.font.SysFont(None,32)
inputFont = pg.font.SysFont('consola', 35)
errorFont = pg.font.SysFont('tahoma',20)
diagramFont = pg.font.SysFont('courier new',25)
#Colour definitions
BackGray = pg.Color('gray60')
screenGray = pg.Color('gray80')
buttonGray2 = pg.Color('gray50')
textColour = pg.Color('navy')
#Screen size set
screen = pg.display.set_mode((400, 400))
clock = pg.time.Clock()
class Button(pg.sprite.Sprite):
def __init__(self, text, x, y, width, height, colour, enabled):
super().__init__()
self.image = pg.Surface((width, height))
self.image.fill(colour)
self.rect = self.image.get_rect()
txt = buttonFont.render(text, True, textColour)
txtRect = txt.get_rect(center = self.rect.center)
self.image.blit(txt, txtRect)
self.rect.topleft = x, y
self.enabled = enabled
def isPressed(self, event):
if self.enabled == True:
if event.type == pg.MOUSEBUTTONDOWN:
if self.rect.collidepoint(event.pos):
return True
return False
def Function():
background = pg.Surface(screen.get_size())
background.fill(screenGray)
Button1 = Button('Encrypt',100,100,125,50,buttonGray2,True)
Button2 = Button('Decrypt',100,200,125,50,buttonGray2,True)
buttonsGroup = pg.sprite.Group(Button1,Button2)
ACTIONPRINT = False
Active1 = False
while True:
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit()
elif Button1.isPressed(event):
print("1")
Active1 = True
elif Button2.isPressed(event):
print("2")
if Active1 == True:
ACTIONPRINT = True
buttonsGroup = pg.sprite.Sprite.remove(Button2)
screen.blit(background,(0,0))
buttonsGroup.draw(screen)
pg.display.flip()
clock.tick(60)
Function()
上面是按钮类的代码,以及一个运行两个按钮的简单函数。我想要做的是在按下一个按钮时将其中一个按钮移除,这些按钮被设置为精灵。当按钮从组中移除时,我相信它会在按下一个按钮后从屏幕上消失。
上面的代码会返回错误消息,指出有AttributeError: 'NoneType' object has no attribute 'draw'
。但是,在另一个程序中,当它确实有效时,它表示在Sprite.remove
方法中,参数必须是序列而不是按钮 - 这是什么意思?
我已经在网上看了,所有删除sprite的例子都在一个类中。这是否意味着实现这一目标的唯一方法是改变类?
或者精灵仍然可以从课外移除,如果是这样,它是如何完成的?
欢迎任何其他方法
提前致谢!
答案 0 :(得分:1)
sprite.Group.remove
没有返回任何内容,它会从调用它的组中删除精灵,而不是:
buttonsGroup = pg.sprite.Sprite.remove(Button2)
尝试:
buttonsGroup.remove(Button2)