variables - 如何在 Pygame 中将输入值存储为变量
问题描述
我在 Pygame 中有一个输入框类,在其中我只输入数字,我想要的是,每次我按 ENTER 时,这个值都会存储在一个变量中,以便从另一个函数中使用。谢谢大家。这是输入框代码:
class InputBox:
def __init__(self, x, y, w, h, text=''):
self.rect = pg.Rect(x, y, w, h)
self.color = COLOR_INACTIVE
self.text = text
self.txt_surface = FONT.render(text, True, self.color)
self.active = False
def handle_event(self, event):
if event.type == pg.MOUSEBUTTONDOWN:
# If the user clicked on the input_box rect.
if self.rect.collidepoint(event.pos):
self.active = not self.active
else:
self.active = False
self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE
if event.type == pg.KEYDOWN:
if self.active:
if event.key == pg.K_RETURN:
print(self.text)
self.text = ''
elif event.key == pg.K_BACKSPACE:
self.text = self.text[:-1]
else:
self.text += event.unicode
self.txt_surface = FONT.render(self.text, True, self.color)
def update(self):
width = max(200, self.txt_surface.get_width()+10)
self.rect.w = width
def draw(self, screen):
screen.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))
pg.draw.rect(screen, self.color, self.rect, 2)
def main():
...
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
for box in input_boxes:
box.handle_event(event)
for box in input_boxes:
box.update()
screen.fill((30, 30, 30))
for box in input_boxes:
box.draw(screen)
pg.display.flip()
clock.tick(30)
解决方案
这个例子是否有助于您理解这个概念:
user_input = {'user_input': []}
class UserInput:
def __init__(self):
self.input_ = input('Input something: ')
user_input['user_input'].append(self.input_)
ask = UserInput()
print(user_input)
如果您想在说一个函数中使用字典中的值,您可以像这样访问该值:
dict_name['key_name']
将访问可以是列表的值,以及整数、元组、另一个字典、字符串,基本上是上面所见的变量名称,因此在函数中可以像这样使用它:
your_func(user_input['user_input'][0])
例如,如果您对函数的第一个参数是附加到user_input['user_input']
列表的第一项,在这种情况下,这将是用户输入的内容
推荐阅读
- ios - iOS Swift Mi Scale 2 蓝牙 称重
- ios - SwiftUI 2个问题但很简单,关于searchBar和list的backgroundImage
- arrays - 未能在 Mongo 中正确执行更新
- c# - 是否可以在 C# XML 文档中引用 const 字段的值?
- python - 可以在没有“返回 Send_file”的情况下调用 Send_File 吗?
- python - 如何设置我的 mainWindow 的 sizePolicy?
- python - 在抽象基类中定义 @property.setter 会产生 AttributeError
- c - C - 将项目添加到数组
- bash - Bash 创建新目录并将每行的内容写入新目录中的文件
- python - 是否有一种 Python 的方式来引用 for 循环内的迭代器变量名称?