[英]How draw button in window in pygame
如果我單擊服務器啟動新游戲的選定區域,我的程序中有此代碼。 如何在這個地方出現按鈕或帶有文本“新游戲”的方塊?
with socket.create_connection((SERVER, PORT)) as sock:
with context.wrap_socket(sock, server_hostname="localhost") as client:
session_id = None
while True:
#command = str(input("Podaj komendę"))
#command = translate_pos_to_number(pos[0] // 200, pos[1] // 200)
czy_wyjsc = True
while czy_wyjsc:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.MOUSEBUTTONDOWN:
if pygame.mouse.get_pressed()[0]: # [0] Jeśli lewy przycisk myszki jest kliknięty
pos = pygame.mouse.get_pos()
print(pos[0] // 200, pos[1] // 200)
czy_wyjsc = False
break
surface.fill((20, 189, 172))
grid.draw(surface)
pygame.display.flip()
if (pos[0] // 200 == 1, pos[1] // 200 == 3):
command = "start"
if command == "start":
login = np.random.randint(100, 999)
msg_start = f'To:SER\r\nLogin:{login}\r\nContent-length:5\r\nMessage:START\r\n\r\n'
client.sendall(msg_start.encode())
要在 pygame 中創建一個按鈕,首先需要在 python 程序中添加一個字體,然后創建一個 label 以在該按鈕中顯示一些文本:
font = pygame.font.SysFont("monospace", 30)
label = font.render("SomeText", 1, [COLOR])
之后,您需要在屏幕上創建一個矩形:
pygame.draw.rect(YOUR_SCREEN, YOUR_COLOR ,(X_POS,Y_POS,X_SIZE,Y_SIZE),1)
YOUR_SCREEN.blit(label,(X_POS,Y_POS))
之后,您只需在 pygame 事件中添加碰撞:
for events in pygame.event.get():
if events.type == pygame.QUIT:
pygame.quit()
if events.type == pygame.MOUSEBUTTONDOWN:
if pygame.Rect(X_POS,Y_POS,X_SIZE,Y_SIZE).collidepoint(pygame.mouse.get_pos()):
Your_Function() #Your_Function is the function you want to execute when clicking the button.
希望對您有所幫助,(如果您有任何問題,請隨時提問)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.