Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

python - How can I add an image or icon to a button rectangle in Pygame?

I am a newbie to Pygame and I have created already the codes for my button but I still have a problem because I don't know how will I put an image instead of the solid color red in a rectangle. Here is my codes, hope you can help!

def button(x, y, w, h, ic, ac, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + w > mouse[0] > x and y + h > mouse[1] > y: 
        pygame.draw.rect(screen, ac, (x, y, w, h))
        if click[0] == 1 and action!= None:
            if action == "continue":
                quiz()

    else:
        pygame.draw.rect(screen, ic, (x, y, w, h))  
    pygame.display.update()

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    screen.blit(randomList, [0, 0])
    button(399, 390, 300, 50, red, brightRed, "continue")
    pygame.display.update()
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

All you have to do is to load an image:

my_image = pygame.image.load('my_image.png').convert_alpha()

And blit it an top of the rectangle:

def button(x, y, w, h, ic, ac, img, imgon, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    rect = pygame.Rect(x, y, w, h)
    on_button = rect.collidepoint(mouse)
    if on_button:
        pygame.draw.rect(screen, ac, rect)
        screen.blit(imgon, imgon.get_rect(center = rect.center))
    else:
        pygame.draw.rect(screen, ic, rect)
        screen.blit(img, img.get_rect(center = rect.center))

    if on_button:  
        if click[0] == 1 and action!= None:
            if action == "continue":
                quiz()

image = pygame.image.load('my_image.png').convert_alpha()
imageOn = pygame.image.load('my_image_on.png').convert_alpha()
while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()

    screen.blit(randomList, [0, 0])
    button(399, 390, 300, 50, red, brightRed, image, imageOn, "continue")
    pygame.display.update()


In pygame a button is nothing more than a pygame.Surface object. It is completely irrelevant whether a text or an image is on the button. I recommend to represent the buttons by pygame.sprite.Sprite objects.

See also Pygame mouse clicking detection respectively Mouse and Sprite.

Minimal example:

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, filename):
        super().__init__() 
        img = pygame.image.load(filename).convert_alpha()
        self.original_image = pygame.Surface((70, 70))
        self.original_image.blit(img, img.get_rect(center = self.original_image.fill((127, 127, 127)).center))
        self.hover_image = pygame.Surface((70, 70))
        self.hover_image.blit(img, img.get_rect(center = self.hover_image.fill((228, 228, 228)).center))
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        self.hover = self.rect.collidepoint(pygame.mouse.get_pos())
        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, 'Apple64.png'),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, 'Banana64.png'),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, 'Pear64.png'),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, 'Plums64.png'),
])

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()

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

pygame.quit()
exit()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...