首页 > 解决方案 > 如何从 pygame 菜单中的 text_input 字段中获取值?

问题描述

我正在尝试应用 pygame-menu 库(https://pygame-menu.readthedocs.io)。如何从菜单的文本输入字段中提取“名称”值 - 当我开始游戏时此字段包含的值,即严格在我按下“播放”并进一步处理此值时 - 传递给我的课'游戏'。无法弄清楚文档。也许有人遇到过这个?

import pygame
import pygame_menu

# A class that defines the game environment and launches the gameplay
# Works successfully without a menu
from game import Game

# I need this function from `button('Play', start_the_game)` to start the game
# and NAME is the value that I need to extract from the field 'Name' and pass it
# to the instance of me class Game
def start_the_game(NAME):
    Game(NAME).run()    # Launches the actual game


pygame.init()
screen = pygame.display.set_mode(900, 600)
screen.fill((0,0,0))

menu = pygame_menu.Menu("Let's play!", 400, 300,
                        theme=pygame_menu.themes.THEME_DARK)

menu.add.text_input('Name :', default='A Player')
menu.add.button('Play', start_the_game)
menu.add.button('Quit', pygame_menu.events.EXIT)

menu.mainloop(screen)

标签: pythonpygamemenupygame-menu

解决方案


看起来你应该尝试: player_name = menu.add.text_input('Name :', default='A Player') 然后尝试: start_the_game(player_name.get_value())

根据文档,更标准的方法可能是这样的: player_name = menu.add.text_input('Name :', default='A Player', onchange=get_name) 然后定义一个函数,如:

def get_name(value):
    player_name = value

我对此进行了测试,这两种方法都可以获取值,尽管这两种方法需要在正确的时间传递值的方法略有不同。澄清一下,这将获取值并在调用时将其传递给您的 start_the_game 函数:

name_box = menu.add.text_input('Name :', default='A Player')
menu.add.button('Play', start_the_game, name_box)

如果你的 start_the_game 函数是这样的:

def start_the_game(NAMEBOX):
    GAME(NAMEBOX.get_value()).run()

推荐阅读