Menu Pygame菜单单击以运行

Menu Pygame菜单单击以运行,menu,click,pygame,Menu,Click,Pygame,在pygame游戏的主菜单类中,我试图调用一个函数。基本上,我有一本字典: if __name__ == "__main__": functions = {"start": main, "Quit": terminate} 单击菜单项后,我在类中调用这些函数的方法是: def runMenu(self): mainloop = True while mainloop: self.__clock.tick(50) for event in

在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)的对象引用。我不知道该如何避开这个问题。我看到了一个例子,其中一个家伙自己调用函数。_ufunctionsitem.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>
>>> 
回溯(最近一次呼叫最后一次):
文件“/Users/tjleggz/Documents/CS 110/squirrel/squirrel.py”,第501行,在
game.runMenu()
文件“/Users/tjleggz/Documents/CS 110/squirrel/squirrel.py”,第138行,在runMenu中
self._函数[item]()#不能调用bc它不是同一个对象,只是对对象的引用还是什么@
关键错误:
>>> 

谢谢

我希望我正确理解这个问题;从回溯来看,它似乎是您的
self。items
包含
MenuItem
对象,而不是作为字典键的字符串。您可以通过两种方式解决此问题,例如,您可以在初始化
MenuItem
的每个实例时,为它们指定一个
text
属性,稍后可以使用
item.text
进行检查

一种更好、更少冗余的方法(而不是像现在这样使用函数字典)可能是在单击时将
函数传递给每个
菜单项
实例,然后只需编写

if item.isMouseSelecting(pygame.mouse.get_pos()):
    item.on_click()

我不太清楚你的意思…这是我的第一节编程课。你能给我举个例子吗?点击是pygame的一部分还是你的意思是创建我自己的?可能是