jc235
jc235

Reputation: 1

Use an image as a button tkinter python 3.6

I am looking to use images as buttons for my rock paper scissors game however I can only find answers to older versions of python using modules such as PIL which are not available in 3.6, any help would be grateful (using jpg files if that's any help) thanks

Upvotes: 0

Views: 362

Answers (1)

Technophobe01
Technophobe01

Reputation: 8666

Here is a brief example:

Code Example:

import pygame


# --- class ---


class imageButton(object):
    def __init__(self, position, size):

        image1 = pygame.image.load('rock.png')
        image2 = pygame.image.load('paper.png')
        image3 = pygame.image.load('scissors.png')


        self._images = [
            pygame.Surface(size),
            pygame.Surface(size),
            pygame.Surface(size),
        ]


        # create 3 images
        self._images[0].blit(image1, image1.get_rect())
        self._images[1].blit(image2, image2.get_rect())
        self._images[2].blit(image3, image3.get_rect())

        # get image size and position
        self._rect = pygame.Rect(position, size)

        # select first image
        self._index = 0

    def draw(self, screen):

        # draw selected image
        screen.blit(self._images[self._index], self._rect)

    def event_handler(self, event):

        # change selected color if rectange clicked
        if event.type == pygame.MOUSEBUTTONDOWN:  # is some button clicked
            if event.button == 1:  # is left button clicked
                if self._rect.collidepoint(event.pos):  # is mouse over button
                    self._index = (self._index + 1) % 3  # change image

# --- main ---

# init

pygame.init()

screen = pygame.display.set_mode((320, 110))

# create buttons

button1 = imageButton((5, 5), (100, 100))
button2 = imageButton((110, 5), (100, 100))
button3 = imageButton((215, 5), (100, 100))

# mainloop

running = True

while running:

    # --- events ---

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

        button1.event_handler(event)
        button2.event_handler(event)
        button3.event_handler(event)

    # --- draws ---

    button1.draw(screen)
    button2.draw(screen)
    button3.draw(screen)

    pygame.display.update()

    # --- the end ---

pygame.quit()

Image Files

rock paper scissors

Example Application Run:

pygame window, showing rock, paper, and scissors

Upvotes: 1

Related Questions