简体   繁体   中英

Use an image as a button tkinter python 3.6

我希望将图像用作剪刀石头布游戏的按钮,但是我只能使用3.6中不可用的模块(例如PIL)找到旧版本python的答案,不胜感激(如果有帮助,请使用jpg文件) ) 谢谢

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

岩石 纸 剪刀

Example Application Run:

pygame窗口,显示石头,纸和剪刀

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM