问题描述
我在 Pygame 中有一个输入框类,在其中我只输入数字和我想要的,就是每次我按 ENTER 时,这个值都会存储在一个变量中,以供另一个函数使用。谢谢大家。 这是输入框代码:
class InputBox:
def __init__(self,x,y,w,h,text=''):
self.rect = pg.Rect(x,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,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']
列表的第一个项目,在这种情况下将是用户输入的内容
向类 InputBox
添加列表属性并将新输入附加到列表中:
class InputBox:
def __init__(self,x,y,w,h,text=''):
# [...]
self.input_list = []
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:
input_list.appned(self.text)
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)
您可以访问每个框的输入列表:
last_inout = input_boxes[0].input_list[-1]