在作为pygame游戏主菜单的类中,我试图调用一个函数。基本上,我有一本字典:
if __name__ == "__main__":
functions = {"start": main, "Quit": terminate}
在单击菜单项时,我在课堂上调用这些内容的方法是:
def runMenu(self):
mainloop = True
while mainloop:
self.__clock.tick(50)
for event in pygame.event.get():
#print(pygame.mouse.get_pressed())
if event.type == pygame.QUIT:
mainloop == False
terminate()
if event.type == pygame.MOUSEBUTTONDOWN:
for item in self.items:
#print(item.isMouseSelecting(pygame.mouse.get_pos()))
if item.isMouseSelecting(pygame.mouse.get_pos()):
#print(self.__functions)
self.__functions[item]() #initialized in the __init__ so that it holds my dictionary in self.__functions
但是,我无法调用每个函数的对象引用(main和terminate)。我不确定如何解决这个问题。我看到一个例子,那个人通过self .__ functionsitem.text调用这个函数但是这对我不起作用,因为我无法在.text方法上找到任何东西并且在这样做时会出现属性错误。
我的错误是我的错误:
Traceback (most recent call last):
File "/Users/tjleggz/Documents/CS 110/squirrel/squirrel.py", line 501, in <module>
game.runMenu()
File "/Users/tjleggz/Documents/CS 110/squirrel/squirrel.py", line 138, in runMenu
self.__functions[item]() #cant call bc its not same object, just a ref to object or something???@
KeyError: <__main__.MenuItem object at 0x29758c8>
>>>
谢谢!
答案 0 :(得分:0)
我希望我能正确理解这个问题;从回溯看来,您的self.items
包含MenuItem
个对象,而不是字典的关键字。您可以通过几种方式解决此问题,例如,您可以在初始化时为MenuItem
text
属性提供item.text
属性,稍后您可以使用on_click
进行检查。
更好,更少冗余的方法(而不是像现在这样使用函数字典)可能是将MenuItem
函数传递给你制作的每个if item.isMouseSelecting(pygame.mouse.get_pos()):
item.on_click()
个实例,然后你只需要写
{{1}}