问题描述
我正在尝试在我的游戏中放置一个播放按钮。当我启动游戏时,我点击了播放按钮,它给了我一个错误
Traceback (most recent call last):
File "C:\Users\Zee_S\OneDrive\Desktop\python projects\lil Shooter\Player\Lil Shooter.py",line 370,in <module>
game_intro()
File "C:\Users\Zee_S\OneDrive\Desktop\python projects\lil Shooter\Player\Lil Shooter.py",line 336,in game_intro
button("LETS PLAY!",20,450,115,50,green,bright_green,run)
File "C:\Users\Zee_S\OneDrive\Desktop\python projects\lil Shooter\Player\Lil Shooter.py",line 308,in button
action()
TypeError: 'bool' object is not callable
[Finished in 8.3s]
我已经查看了这个“bool”的代码,但我找不到任何东西。这是按钮和标题屏幕的代码
def text_objects(text,font):
textSurface = font.render(text,True,black)
return textSurface,textSurface.get_rect()
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x + w > mouse[0] > x and y + h > mouse[1] > y:
pygame.draw.rect(screen,(x,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(screen,h))
smallText = pygame.font.SysFont("comicsansms",20)
textSurf,textRect = text_objects(msg,smallText)
textRect.center = ((x + (w / 2)),(y + (h / 2)))
screen.blit(textSurf,textRect)
def quitgame():
pygame.quit()
quit()
def game_intro():
intro = True
while intro:
for event in pygame.event.get():
# print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.fill(white)
largeText = pygame.font.SysFont("comicsansms",115)
TextSurf,TextRect = text_objects("Lilshooter",largeText)
TextRect.center = ((display_width / 2),(display_height / 2))
screen.blit(TextSurf,TextRect)
button("LETS PLAY!",run)
button("Quit",480,100,red,bright_red,quitgame)
pygame.display.update()
clock.tick(15)
这是我在游戏循环中调用它的地方
run = True
game_intro()
while run:
[...]
我可以得到这个问题的帮助吗
解决方法
函数 button
的最后一个参数需要是一个函数。因此它不能是 run
,因为 run
是一个布尔值。
如果要在按钮按下时更改 intro
变量的状态,请编写一个 startGame
函数:
def startGame():
global intro
intro = False
将 startGame
传递给 button
,而不是 run
:
button("LETS PLAY!",20,450,115,50,green,bright_green,startGame)
注意变量 intro
必须是全局命名空间中的变量:
(见global
statement)
intro = True
def game_intro():
global intro
while intro:
# [...]
,
名称 action
有问题。你的错误是
输入按钮 行动() 类型错误:“bool”对象不可调用
这意味着您在代码中的某处使用 action
作为函数,但它是 bool
。
首先,让我们看看 action
函数中的 button()
。我们看到它是一个输入参数,并且在 if
检查之后有可能 action
将作为函数被调用:问题出现是因为您对 action
进行的唯一检查是它不是 None,所以如果它不是 None 但也不是函数,它将引发错误。
在代码中的某处调用 button()
并将 True
(或等效变量)作为 action
参数传递给它。
特别是,按钮被 game_intro()
调用两次:
button("LETS PLAY!",run)
button("Quit",480,100,red,bright_red,quitgame)
由于在 game_intro()
内没有初始化 run,我假设变量 run
与 while 循环外的初始化相同 (run = True
)。