我想將用戶輸入的文本輸出到屏幕。每次用戶按下返回鍵時,輸入的文本都應該顯示在屏幕上。對於文本輸入,我使用這個[text_input模塊](https://github.com/Nearoo/pygame-text-input)。將用戶文本輸入屏幕
這裏是我想出了迄今爲止代碼:
import pygame_textinput
import pygame
pygame.init()
# Set some parameters
duration = 5.0
time = pygame.time.get_ticks()/1000
screen = pygame.display.set_mode((400, 400))
clock = pygame.time.Clock()
yoffset = 5
# Function that positions user input rects on screen
def renderInput(text, xoffset, yoffset):
font = pygame.font.SysFont("arial", 20)
renderText = font.render(text, False, (0, 0, 0))
rectText = renderText.get_rect()
rectText = rectText.move((0 + xoffset), (screen.get_height()/2 + yoffset))
return renderText, rectText
# Fills the screen once at the beginning
screen.fill((225, 225, 225))
while (pygame.time.get_ticks()/1000) < time + duration:
# creat new text input object on every trial
textinput = pygame_textinput.TextInput()
while True:
# Fills the surface after each keypress
screen.fill((225, 225, 225))
# Check events
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
exit()
# Feed with events every frame
# This evaluates to True once Return is pressed
if textinput.update(events):
userInput = textinput.get_text()
yoffset += 20
break
# Blit surface onto the screen
screen.blit(textinput.get_surface(), (10, 10))
# Update screen
pygame.display.update()
clock.tick(30)
# Blits user input to screen each time "Return" is pressed
# First get input text and the rectangle of the text
text, textrect = renderInput(userInput, 5, yoffset)
# Then blit it to the screen
screen.blit(text, textrect)
pygame.display.update()
我的問題是,如果我不while循環來處理輸入中的每個按鍵之後填充屏幕的阻擊器只適用。如果我這樣做了,那麼每次用戶按下Return鍵後,文本輸入都不會被清除。
因此,有一種方法可以在每次按鍵後重新繪製,並且每次用戶按下返回按鈕後都會顯示下面的文本。
謝謝。
非常感謝這個有用的例子。一旦用戶點擊返回,創建一個新實例返回是一個很好的解決方法。但是,我認爲我沒有足夠詳細地說明我的問題。我有第一個while循環和渲染到屏幕的函數的原因如下:我希望用戶輸入顯示在下面(如您執行的那樣),但是當用戶輸入其他內容並再次返回時,該輸入應該顯示在已經顯示的輸入下方。這個過程一直持續到計時器用完爲止(第一次while循環)。 – Ivan
在這種情況下,我可能會渲染文本表面並將其附加到列表中。然後你可以遍歷這個曲面列表,並用主循環中的偏移量對它們進行處理。 – skrx