[英]How to move a button in pygame?
import pygame
pygame.init()
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Blackjack")
icon = pygame.image.load('jack.jpg')
pygame.display.set_icon(icon)
over_font = pygame.font.Font('GOODDP__.TTF', 64)
jack = pygame.image.load('rsz_jack.png')
jackX = 295
jackY = 100
running = True
def jack_title():
screen.blit(jack, (jackX, jackY))
def display_title_text():
over_text = over_font.render("Blackjack", True, (0, 0, 0))
screen.blit(over_text, (292, 300))
def start_button():
button = pygame.Rect(50, 100, 100, 50)
pygame.draw.rect(screen, [0, 255, 0], button)
button.move(0, 0)
over_text = over_font.render("START!", True, (0, 0, 0))
screen.blit(over_text, (0, 75))
clicked = pygame.mouse.get_pressed()
if clicked[0] == 1:
print('Clicked left button!')
elif clicked[1] == 1:
print('Clicked middle button!')
elif clicked[-1] == 1:
print('Clicked right button!')
else:
pass
def quit_button():
button = pygame.Rect(50, 100, 100, 50)
pygame.draw.rect(screen, [255, 0 ,0], button)
def display_gameover_message():
over_text = over_font.render("GAME OVER", True, (0, 0, 0))
screen.blit(over_text, (292, 300))
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((150, 173, 252))
jack_title()
display_title_text()
start_button()
quit_button()
pygame.display.update()
我正在尝试将我的 start_button() 移动到屏幕底部,但我不知道如何移动它,因为我尝试pygame.Rect.move()
和pygame.Rect.move_ip()
但它们似乎没有移动按钮。 我想重新定位按钮,以便一旦我单击该按钮,它就可以让我退出游戏的标题页。
启动按钮的位置由 function start_button 中的pygame.Rect
start_button
button
定义。 第二个参数定义按钮的顶部。 只需更改第二个参数,例如height-50
而不是 100:
def start_button():
# button = pygame.Rect(50, 100, 100, 50)
button = pygame.Rect(50, height-50, 100, 50)
# [...]
另一种可能性是在定义矩形后,将button
的 .top 设置为等于.top
的底部:
def start_button():
button = pygame.Rect(50, 100, 100, 50)
button.bottom = height
# [...]
请注意,Rect object 有几个虚拟属性,可用于移动和对齐矩形。 请参阅pygame.Rect
。
如果你想在应用程序的后面移动按钮,那么你必须在全局命名空间中定义start_button_rect
:
start_button_rect = pygame.Rect(50, 100, 100, 50)
def start_button():
pygame.draw.rect(screen, [0, 255, 0], start_button_rect)
# [...]
现在,您可以更改start_button_rect
,例如通过move_ip
:
start_button_rect.move_ip(0, 400)
或通过设置虚拟属性:
start_button_rect.bottom = height
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.