[英]How would I go about making clickable text in Pygame?
基本上,这是我在Pygame中的代码的一部分:
button_text=pygame.font.Font("C:\Windows\Fonts\Another Danger - Demo.otf",35)
textSurface,textRect=text_objects("Start game",button_text)
textRect.center=(105,295)
screen.blit(textSurface,textRect)
这是我想要变成可点击格式的文本,这样当有人按下文本时,它可以运行一个函数,例如运行下一个可能的事情。
任何帮助将不胜感激。
谢谢。
pygame没有Bottons所以你可以在这里做的是当用户按下任何鼠标按钮你将获得鼠标位置使用此pygame.mouse.get_pos()
并且如果鼠标pos在文本内,那么你知道他按下了文本
这是示例代码:
import pygame,sys
from pygame.locals import *
screen=pygame.display.set_mode((1000,700))
pygame.init()
clock = pygame.time.Clock()
tx,ty=250,250
while True :
for event in pygame.event.get():
if event.type==QUIT :
pygame.quit()
quit()
if event.type== pygame.MOUSEBUTTONDOWN and event.button == 1:
mouse=pygame.mouse.get_pos()
if mouse[0]in range ( tx,tx+130) and mouse[1]in range ( ty,ty+20):
print (" you press the text ")
myfont = pygame.font.SysFont("Marlett",35)
textsurface = myfont.render(("Start game"), True, (230,230,230))
screen.blit(textsurface,(tx,ty))
pygame.display.update()
clock.tick(60)
我在这个例子中使用了tx和ty的大小,但是你可以使用rect同样的东西
从font.render
返回的曲面获取矩形,并将其用于碰撞检测和blit位置。
import sys
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock()
font = pg.font.Font(None, 30)
text_surface = font.render('text button', True, pg.Color('steelblue3'))
# Use this rect for collision detection with the mouse pos.
button_rect = text_surface.get_rect(topleft=(200, 200))
done = False
while not done:
for event in pg.event.get():
if event.type == pg.QUIT:
done = True
if event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
# Use event.pos or pg.mouse.get_pos().
if button_rect.collidepoint(event.pos):
print('Button pressed.')
screen.fill((40, 60, 70))
screen.blit(text_surface, button_rect)
pg.display.flip()
clock.tick(30)
if __name__ == '__main__':
pg.init()
main()
pg.quit()
sys.exit()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.