python - 如何从 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)
解决方案
看起来你应该尝试:
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()
推荐阅读
- c++ - 在下面提到的代码中,我希望输出按调用的降序排列
- angular - 为什么 ExpressJS 忽略 Access-Control-Allow-Origin 设置?
- ios - 按下通知后反应原生应用程序崩溃 [iOS]
- python - python 正则表达式匹配包括新行在内的完整段落
- python - 怎么做翻译?
- java - 如何自动删除 log4j2 中的旧日志文件
- c# - 如何在私有 void 中使用 Xamarin.form 中的对象(如条目)?
- google-apps-script - 如何避免在 google-sheet 应用程序脚本中重定向
- vim - 有没有办法执行 txt 文件中的 vim 命令以及文本?
- javascript - 我如何使响应机器人不继续响应?