PyGame에서 옵션 버튼을 구현하고 버튼 색상을 변경하려면 어떻게해야합니까?

Nov 29 2020

Pls는 버튼을 눌렀을 때 버튼의 색상을 변경하는 방법을 제안하고 두 번째 버튼을 누르면 첫 번째 버튼의 색상이 기본 색상으로 변경됩니다.

예를 들어 STRAIGHT 버튼을 클릭하면 버튼이 녹색으로 바뀌고, LEFT 버튼을 클릭하면 왼쪽 버튼이 녹색으로 바뀌고 STRAIGHT 버튼이 기본 색상 인 흰색이됩니다. 미리 감사드립니다 :)

암호:

def draw_button(self):

    global clicked
    action = False

    # get mouse position
    pos = pygame.mouse.get_pos()

    # create pygame Rect object for the button
    button_rect = Rect(self.x, self.y, self.width, self.height)

    # check mouseover and clicked conditions
    if button_rect.collidepoint(pos):
        if pygame.mouse.get_pressed()[0] == 1:
            clicked = True
            pygame.draw.rect(screen, self.click_col, button_rect)
        elif pygame.mouse.get_pressed()[0] == 0 and clicked == True:
            clicked = False
            action = True
           
        else:
            pygame.draw.rect(screen, self.hover_col, button_rect)
    else:
        pygame.draw.rect(screen, self.button_col, button_rect)

답변

1 Rabbid76 Nov 29 2020 at 19:01

버튼을 그릴 때 전역 변수에 따라 색상을 설정해야합니다 clicked.

def draw_button(self):

    global clicked
    
    # get mouse position
    pos = pygame.mouse.get_pos()

    # create pygame Rect object for the button
    button_rect = Rect(self.x, self.y, self.width, self.height)

    # check mouseover and clicked conditions
    hover = button_rect.collidepoint(pos)
    if hover and pygame.mouse.get_pressed()[0] == 1:
        clicked = not clicked

    color = self.button_col
    if clicked:
        color = self.click_col
    elif hover:
        color = self.hover_col

    pygame.draw.rect(screen, color, button_rect)

어쨌든 모든 마우스 버튼 pygame.mouse.get_pressed()의 상태 ( True또는 False) 를 나타내는 부울 값 목록을 반환 하므로 만족스럽지 않습니다 . 버튼의 상태는 True버튼을 누르고있는 동안입니다. 이벤트
를 사용해야 MOUSEBUTTONDOWN합니다. MOUSEBUTTONDOWN이벤트는 마우스 버튼을 클릭 할 때 한 번 발생하고 MOUSEBUTTONUP이벤트는 마우스 버튼을 놓을 때 한 번 발생합니다. pygame.event.Event()객체는 마우스 이벤트에 대한 정보를 제공하는 두 개의 속성이 있습니다. pos클릭 한 위치를 저장하는 튜플입니다. button클릭 한 버튼을 저장합니다.


서로 상호 작용해야하는 여러 버튼이있는 경우 단일 clicked상태로는 충분하지 않습니다. 각 버튼에 대해 별도의 "클릭"상태가 필요합니다. 1 버튼의 클릭 상태가가되면 True다른 키의 상태는로 설정되어야합니다 False. 이를 위해 RadioButton클래스 를 구현하는 것이 좋습니다 .

마우스 및 스프라이트를 참조하십시오 .

최소한의 예 :

import pygame

class RadioButton(pygame.sprite.Sprite):
    def __init__(self, x, y, w, h, font, text):
        super().__init__() 
        text_surf = font.render(text, True, (0, 0, 0))
        self.button_image = pygame.Surface((w, h))
        self.button_image.fill((96, 96, 96))
        self.button_image.blit(text_surf, text_surf.get_rect(center = (w // 2, h // 2)))
        self.hover_image = pygame.Surface((w, h))
        self.hover_image.fill((96, 96, 96))
        self.hover_image.blit(text_surf, text_surf.get_rect(center = (w // 2, h // 2)))
        pygame.draw.rect(self.hover_image, (96, 196, 96), self.hover_image.get_rect(), 3)
        self.clicked_image = pygame.Surface((w, h))
        self.clicked_image.fill((96, 196, 96))
        self.clicked_image.blit(text_surf, text_surf.get_rect(center = (w // 2, h // 2)))
        self.image = self.button_image
        self.rect = pygame.Rect(x, y, w, h)
        self.clicked = False
        self.buttons = None

    def setRadioButtons(self, buttons):
        self.buttons = buttons

    def update(self, event_list):
        hover = self.rect.collidepoint(pygame.mouse.get_pos())
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if hover and event.button == 1:
                    for rb in self.buttons:
                        rb.clicked = False
                    self.clicked = True
        
        self.image = self.button_image
        if self.clicked:
            self.image = self.clicked_image
        elif hover:
            self.image = self.hover_image


pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()
font50 = pygame.font.SysFont(None, 50)

radioButtons = [
    RadioButton(50, 40, 200, 60, font50, "option 1"),
    RadioButton(50, 120, 200, 60, font50, "option 2"),
    RadioButton(50, 200, 200, 60, font50, "option 3")
]
for rb in radioButtons:
    rb.setRadioButtons(radioButtons)
radioButtons[0].clicked = True

group = pygame.sprite.Group(radioButtons)

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()
GameDev Nov 29 2020 at 18:15
your_button_rect = pygame.Rect(x,y,width,height)
color = (0,0,0)
pos = pygame.mouse.get_pos()
def change_button_color():
    if your_button_rect.colliderect(pos):
        if event.type == pygame.MOUSEBUTTONDOWN: #checks if mouse button is pressed down while the cursor is on the rectangle
            color = (your_desired_Color_RGBvalue)

while True:
    pygame.draw.rect(screen,color,your_button_rect)
    change_button_color()