gpt4 book ai didi

python - 在鼠标单击pygame时预览键盘输入和blit文本

转载 作者:太空宇宙 更新时间:2023-11-04 09:48:36 25 4
gpt4 key购买 nike

我正在尝试将用户在屏幕上键入的内容显示为预览,当他们用鼠标左键单击时,它会将文本 blits 到屏幕上。

from pygame import *

init()
screen = display.set_mode((640, 480))
clock = time.Clock()
running = True

font = font.SysFont("comicsansms", 72) # Default font
textC = "a" # Stores user input
text = font.render(textC, True, (255,0,0)) # Render Text

while running:

mx, my = mouse.get_pos()
mb = mouse.get_pressed()
for e in event.get():
if e.type == QUIT:
running = False

if e.type == KEYDOWN:
print(textC)
if key.get_pressed()[K_BACKSPACE]:
textC = textC[:-1] # removes last letter
else:
textC += e.unicode # adds letter

screen.fill((255, 255, 255)) #fill screen white
screen.blit(text, (mx, my)) # display text

display.flip()
clock.tick(60)

quit()

最佳答案

首先,您没有正确捕获鼠标事件。您可以像使用 KEYDOWN 键事件一样使用 MOUSEBUTTONDOWN 事件,然后使用 mouse.get_pressed 知道哪个鼠标按钮被按下.

其次,问题在于每次执行 screen.fill 时,所有表面都会被删除,因此有必要以某种方式跟踪文本和渲染文本的位置。它可以是一个列表。

所以你的代码可以看起来像这样

from pygame import *

init()
screen = display.set_mode((640, 480))
clock = time.Clock()
running = True

font = font.SysFont("comicsansms", 72) # Default font
textC = "a" # Stores user input
text = font.render(textC, True, (255,0,0)) # Render Text

text_rendered = []

def rerender_text():
for surface, pos in text_rendered:
screen.blit(surface, pos) # display text

while running:
screen.fill((255, 255, 255)) # fill screen white
mx, my = mouse.get_pos()
for e in event.get():
if e.type == QUIT:
running = False

if e.type == KEYDOWN:
keys = list(key.get_pressed())
index = keys.index(1)
if key.get_pressed()[K_BACKSPACE]:
textC = textC[:-1] # removes last letter
else:
textC += e.unicode # adds letter

if e.type == MOUSEBUTTONDOWN:
if mouse.get_pressed()[0]: # Left click
screen.blit(text, (mx, my)) # display text
# save the text and the position for rerendering
text_rendered.append((text,(mx,my)))


text = font.render(textC, True, (255, 0, 0)) # Render Text
rerender_text()
screen.blit(text, (mx, my)) # display text
display.flip()
clock.tick(60)

quit()

关于python - 在鼠标单击pygame时预览键盘输入和blit文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48819905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com