#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()
上面是 Button 类的代码,以及一个运行两个按钮的简单函数。我想做的是,当按下一个按钮时,删除其中一个按钮,这些按钮被设置为 Sprite 。当按钮从组中删除时,我相信按下一个按钮后它应该从屏幕上消失。
上面的代码此时返回一个错误,表示存在 AttributeError: 'NoneType' object has no attribute 'draw'
。然而,在另一个程序中,当它确实工作时,它说在 Sprite.remove
方法中,参数必须是序列而不是按钮 - 这是什么意思?
我在网上查了一下,所有删除 Sprite 的例子都在一个类中。这是否意味着实现此目的的唯一方法是更改类?
或者仍然可以从类外部删除 Sprite 吗?如果可以,该怎么做?
欢迎任何其他方法
提前致谢!
最佳答案
sprite.Group.remove
不返回任何内容,它会从调用它的组中删除 Sprite ,因此:
buttonsGroup = pg.sprite.Sprite.remove(Button2)
尝试:
buttonsGroup.remove(Button2)
关于python - 如何从组中、类之外删除 Sprite : Pygame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47929265/