我有一个用pygame创建的按钮。现在,我想在按下按钮后在屏幕上显示一些文本。但是我想给它一个varibale而不是字符串。我怎么做 ?我尝试将screen.blit(txtSmjerKretanja, (150,150))
添加到if gumbLijevo.collidepoint(mouse_pos)
和if gumbDesno.collidepoint(mouse_pos):
,但是它不起作用。
编辑:
我查看了其他用户的建议主题,但这并不能真正解决我的问题。问题是,我使用某些变量(在本例中为smjerKretanja)而不是诸如“'some string ..'”之类的普通字符串时,程序不会立即显示文本。
import pygame
import sys
def main():
pygame.init()
myfont = pygame.font.SysFont('Arial', 20)
clock = pygame.time.Clock()
fps = 60
size = [500, 500]
bg = [255, 255, 255]
smjerKretanja = 0
screen = pygame.display.set_mode(size)
gumbLijevo = pygame.Rect(20, 20, 100, 30)
gumbDesno = pygame.Rect(150, 20, 100, 30)
txtLijevo = myfont.render('Lijevo', False, (0,0,0))
txtDesno = myfont.render('Desno', False, (0,0,0))
txtSmjerKretanja = myfont.render(str(smjerKretanja), False, (0,0,0))
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.MOUSEBUTTONDOWN:
mouse_pos = event.pos # gets mouse position
# checks if mouse position is over the button
if gumbLijevo.collidepoint(mouse_pos):
# prints current location of mouse
# print('button was pressed at {0}'.format(mouse_pos))
smjerKretanja = smjerKretanja - 10
if smjerKretanja < 0:
smjerKretanja = 350
print smjerKretanja
screen.blit(txtSmjerKretanja, (150,150))
if gumbDesno.collidepoint(mouse_pos):
# prints current location of mouse
# print('button was pressed at {0}'.format(mouse_pos))
smjerKretanja = smjerKretanja + 10
if smjerKretanja > 360:
smjerKretanja = 10
print smjerKretanja
screen.blit(txtSmjerKretanja, (150,150))
screen.fill(bg)
pygame.draw.rect(screen, [255, 0, 0], gumbLijevo)
pygame.draw.rect(screen, [255, 0, 0], gumbDesno)
screen.blit(txtLijevo,(30,20))
screen.blit(txtDesno,(160,20))
pygame.display.update()
clock.tick(fps)
pygame.quit()
sys.exit
if __name__ == '__main__':
main()
答案 0 :(得分:0)
您仅在代码开头更新txtSmjerKretanja,为了不断更新,您需要添加
txtSmjerKretanja = myfont.render(str(smjerKretanja), False, (0,0,0))
while循环