簡體   English   中英

使用圖像作為按鈕Tkinter Python 3.6

[英]Use an image as a button tkinter python 3.6

我希望將圖像用作剪刀石頭布游戲的按鈕,但是我只能使用3.6中不可用的模塊(例如PIL)找到舊版本python的答案,不勝感激(如果有幫助,請使用jpg文件) ) 謝謝

這是一個簡單的示例:

代碼示例:

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

圖像文件

岩石 紙 剪刀

示例應用程序運行:

pygame窗口,顯示石頭,紙和剪刀

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM