使用图像作为按钮tkinter python 3.6

时间:2017-10-26 17:15:24

标签: python python-3.x tkinter

我希望使用图像作为我的石头剪刀游戏的按钮但是我只能使用诸如PIL之类的模块找到旧​​版python的答案,这些模块在3.6中不可用,任何帮助都会感激不尽(使用jpg文件,如果这是任何帮助) 感谢

1 个答案:

答案 0 :(得分:1)

这是一个简短的例子:

代码示例:

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

图像文件

rock paper scissors

示例应用程序运行:

pygame window, showing rock, paper, and scissors