【问题标题】:pygame - What is the code for clicking on an image [duplicate]pygame - 单击图像的代码是什么[重复]
【发布时间】:2016-01-24 20:40:14
【问题描述】:

我正在向我的游戏添加标题屏幕,并且我想添加“播放”按钮,当用户单击它时将启动主游戏。

我已经设置好了一切,但我不确定让鼠标与播放按钮图像交互的命令是什么。

首先,我在主循环之外加载了播放按钮图像

play = pygame.image.load("play.png").convert()

然后,我让它在屏幕上闪烁,后面有一个矩形作为标记

play_button = pygame.draw.rect(screen, WHITE, [365, 515, 380, 180])
screen.blit(play, [350, 500])

【问题讨论】:

标签: python pygame


【解决方案1】:

PyGame 是低级库 - 它没有 GUI 小部件,您必须自己做很多事情。

更容易创建类Button然后多次使用。

这里是 Button 类的示例。当你点击它改变颜色。

event_handler() 检查按钮点击。

import pygame

# --- class ---

class Button(object):

    def __init__(self, position, size):

        # create 3 images
        self._images = [
            pygame.Surface(size),    
            pygame.Surface(size),    
            pygame.Surface(size),    
        ]

        # fill images with color - red, gree, blue
        self._images[0].fill((255,0,0))
        self._images[1].fill((0,255,0))
        self._images[2].fill((0,0,255))

        # 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 = Button((5, 5), (100, 100))
button2 = Button((110, 5), (100, 100))
button3 = Button((215, 5), (100, 100))

# mainloop

running = True

while running:

    # --- events ---

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

        # --- buttons events ---

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

https://github.com/furas/my-python-codes/blob/master/pygame/button-click-cycle-color/main_class.py

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-24
    • 2023-03-03
    • 2013-02-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多