单击鼠标按钮后是否可以在Pygame中放置图像?

时间:2018-09-16 06:58:49

标签: python pygame

因此,我有一个问题似乎无法通过搜索或我自己的知识来解决。

基本上,我有一个程序使图像(在本例中为ball_r.gif)跟随鼠标光标。 (程序在下面)

import pygame as pg




pg.init()
# use an image you have (.bmp  .jpg  .png  .gif)
image_file = "ball_r.gif"



black = (0,0,0)
sw = 800
sh = 800



screen = pg.display.set_mode((sw, sh))
pg.display.set_caption('testprogram')
image = pg.image.load(image_file).convert()



start_rect = image.get_rect()
image_rect = start_rect
running = True
while running:
    event = pg.event.poll()
    keyinput = pg.key.get_pressed()
    if keyinput[pg.K_ESCAPE]:
        raise SystemExit
    elif event.type == pg.QUIT:
        running = False
    elif event.type == pg.MOUSEMOTION:
        image_rect = start_rect.move(event.pos)

    screen.fill(black)
    screen.blit(image, image_rect)
    pg.display.flip()

基本上,我想做的就是单击鼠标左键,然后将图像放置在单击鼠标的位置-但是要注意的是,我需要能够放置尽可能多的图像,并且图像仍然跟随光标。

我希望这是可能的...

_MouseBatteries

1 个答案:

答案 0 :(得分:0)

关键是创建另一个带有标记图像的Surface对象。我提供了工作代码。我也清理了一下。

import pygame as pg

pg.init()

# use an image you have (.bmp  .jpg  .png  .gif)
image_file = "ball_r.gif"

black = (0,0,0)
sw = 800
sh = 800

screen = pg.display.set_mode((sw, sh))
pg.display.set_caption('testprogram')
image = pg.image.load(image_file).convert()

start_rect = image.get_rect()
image_rect = start_rect
running = True

stamped_surface = pg.Surface((sw, sh))

while running:
    event = pg.event.poll()
    keyinput = pg.key.get_pressed()

    if keyinput[pg.K_ESCAPE]:
        raise SystemExit

    elif event.type == pg.QUIT:
        running = False

    elif event.type == pg.MOUSEMOTION:
        image_rect = start_rect.move(event.pos)

    elif event.type == pg.MOUSEBUTTONDOWN:
        stamped_surface.blit(image, event.pos)

    screen.fill(black)
    screen.blit(stamped_surface, (0, 0))
    screen.blit(image, image_rect)
    pg.display.flip()