Pygame 将菜单项绑定到函数(通过单击) [英] Pygame Binding Menu items to functions (by clicking)

查看:54
本文介绍了Pygame 将菜单项绑定到函数(通过单击)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为课堂项目修改 Squirrel Eat Squirrel Pygame.尝试添加带有基本开始"、退出"和设置"按钮的菜单.我在那里有按钮,当鼠标在它们上面滚动时它们会亮起.但是,当我单击它们时,我无法弄清楚如何调用它们各自的功能.我试图通过这个给他们打电话:

def runMenu(self):主循环 = 真而主循环:self.__clock.tick(50)对于 pygame.event.get() 中的事件:如果 event.type == pygame.QUIT:主循环==错误如果 event.type == MOUSEBUTTONDOWN:对于 self.__items 中的项目:#打印(项目)如果 item.isMouseSelecting(pygame.mouse.get_pos()):打印(self.__functions)self.__functions[item]() #HERE <----

我相信这是因为我在 if name == "ma​​in"(见下文)中使用了字典,因此它实际上不是字典,而是它的引用它的位置?如果这是有道理的.(我不太会解释,所以很抱歉)

if __name__ == "__main__":屏幕 = pygame.display.set_mode((640, 480), 0, 32)menuItems = ('开始', '退出', '设置')功能 = {'开始':主要,'退出':终止,'设置':无}pygame.display.set_caption('主菜单')游戏 = MainMenu(屏幕,功能,菜单项)game.runMenu()

它在 shell 中给我的错误:

<预><代码>>>>================================ 重新开始 ==================================>>>({'Start': , 'Settings': None, 'Quit': }, '#'){'Start': , 'Settings': None, 'Quit': }回溯(最近一次调用最后一次): 中的文件/Users/tjleggz/Documents/CS 110/squirrel/squirrel.py",第 501 行game.runMenu()文件/Users/tjleggz/Documents/CS 110/squirrel/squirrel.py",第 138 行,在 runMenu 中self.__functions[item]() #cant call bc 它不是同一个对象,只是一个对对象的引用什么的???@KeyError: <__main__.MenuItem object at 0x29758c8>>>>

谢谢!

class MenuItem(pygame.font.Font):def __init__(self, text, font=None, fontSize=30,fontColor=(255, 255, 255), (posX, posY)=(0, 0)):pygame.font.Font.__init__(self, font, fontSize) #初始化字体模块self.__text = 文本self.__fontSize = fontSizeself.__fontColor = fontColorself.label = self.render(self.__text, 1, self.__fontColor) #not private??self.width = self.label.get_rect().widthself.height = self.label.get_rect().heightself.__posX = posXself.__posY = posYself.position = posX, posYdef set_position(self, x, y):self.position = (x, y)self.__posX = xself.__posY = ydef isMouseSelecting(self, (posX, posY)): #改为条件?!if (posX >= self.__posX and posX <= self.__posX + self.width) 和 \(posY >= self.__posY 和 posY <= self.__posY + self.height):返回真别的:返回错误def setFontColor(self, rgbTuple):self.fontColor = rgbTupleself.label = self.render(self.__text, 1, self.fontColor)

解决方案

您的 self.items 包含 MenuItem 对象,而不是作为字典键的字符串.您可以通过多种方式解决此问题,例如您可以使用 MenuItem__text 属性,我认为这是您要查找的内容.

一种更好的方法(而不是像现在这样使用函数字典)可能是将 on_click 函数传递给您创建的每个 MenuItem 实例,然后你只需要写

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

但是您似乎对编程比较陌生,因此您可能只想使用第一个建议.

Modifying the Squirrel Eat Squirrel Pygame for a class project. Trying to add in a menu, with basic Start, Quit and Settings buttons. I have the buttons there, and they will light up as the mouse scrolls over them. However, I can't figure out how to call their respective functions when I click on them. I am trying to call them by this:

def runMenu(self):
    mainloop = True
    while mainloop:

        self.__clock.tick(50)

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                mainloop == False
            if event.type == MOUSEBUTTONDOWN:
                for item in self.__items:
                    #print(item)
                    if item.isMouseSelecting(pygame.mouse.get_pos()):
                        print(self.__functions)
                        self.__functions[item]() #HERE <----

I believe it is because I am using a dictionary in my if name == "main" (See below) therefore it's not actually the dictionary, but its referencing its location? If that makes sense. (i'm not very good at explaining it, so sorry)

if __name__ == "__main__":
    screen = pygame.display.set_mode((640, 480), 0 , 32)

    menuItems = ('Start', 'Quit', 'Settings')
    functions = {'Start': main, 'Quit': terminate, 'Settings': None}

    pygame.display.set_caption('Main Menu')
    game = MainMenu(screen, functions, menuItems)
    game.runMenu()

The error it gives me in shell:

>>> ================================ RESTART ================================
>>> 
({'Start': <function main at 0x2969ab0>, 'Settings': None, 'Quit': <function terminate at 0x2969cf0>}, '#')
{'Start': <function main at 0x2969ab0>, 'Settings': None, 'Quit': <function terminate at 0x2969cf0>}

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>
>>> 

THANKS!

EDIT:

class MenuItem(pygame.font.Font):
def __init__(self, text, font=None, fontSize=30,
             fontColor=(255, 255, 255), (posX, posY)=(0, 0)):
    pygame.font.Font.__init__(self, font, fontSize) #initializes font module
    self.__text = text
    self.__fontSize = fontSize
    self.__fontColor = fontColor
    self.label = self.render(self.__text, 1, self.__fontColor) #not private??
    self.width = self.label.get_rect().width
    self.height = self.label.get_rect().height
    self.__posX = posX
    self.__posY = posY
    self.position = posX, posY

def set_position(self, x, y):
    self.position = (x, y)
    self.__posX = x
    self.__posY = y

def isMouseSelecting(self, (posX, posY)): #change to conditional?!
    if (posX >= self.__posX and posX <= self.__posX + self.width) and \
    (posY >= self.__posY and posY <= self.__posY + self.height):
        return True
    else:
        return False

def setFontColor(self, rgbTuple):
    self.fontColor = rgbTuple
    self.label = self.render(self.__text, 1, self.fontColor)

解决方案

Your self.items contains MenuItem objects, not strings which are the keys to your dictionary. You can work around this in a couple ways, for example you could use the __text attribute of MenuItem which is I think what you are looking for.

A better way to do this (instead of using a dictionary of functions like you are now) might be to pass an on_click function to each MenuItem instance you make, and then you just have to write

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

however you seem to be relatively new to programming, so you may just want to use the first suggestion.

这篇关于Pygame 将菜单项绑定到函数(通过单击)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆