Python 我如何在Pygame中制作可点击文本?

Python 我如何在Pygame中制作可点击文本?,python,text,pygame,Python,Text,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中的一段代码:

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没有僵尸 因此,当用户按下任何鼠标按钮时,您都可以使用此
pygame.mouse.get_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返回的曲面获取rect,并将其用于碰撞检测和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()

没有任何帮助,或者你在发布之前没有搜索吗?我猜这不是我的问题措辞,谢谢链接,这似乎是我遇到的问题。非常感谢,我会在我的代码中尝试一下。