pygame
怎样改才能让鼠标控制图片移动?
import pygame as pg
import sys
import time
pg.init() #初始化
screen = pg.display.set_mode((400, 400))
pg.display.set_caption("Pygame窗口")
image= pg.image.load("u=4269708609,317730862&fm=253&fmt=auto&app=138&f=JPEG.png")
image = pg.transform.scale(image,(25,25))
clock = pg.time.Clock()#控制FPS
background_color = (255, 255, 255)
while True:
screen.fill((background_color))
screen.blit(image, (0, 0))
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit(0)
elif event.type == pg.MOUSEBUTTONDOWN:
if event.button == 1:
x, y = pg.mouse.get_pos()
x-= image.get_width() / 2
y-= image.get_height() / 2
screen.blit(image, (x, y))
clock.tick(65)
pg.display.flip()
不知道你这个问题是否已经解决, 如果还没有解决的话:我可以帮你解决这个问题。根据你的描述,你想使用pygame实现鼠标控制图片移动的功能。下面是实现这个功能的具体步骤:
import pygame
from pygame.locals import *
image = pygame.image.load("image.png")
pygame.init() # 初始化pygame
screen = pygame.display.set_mode((800, 600)) # 创建窗口大小为800x600的窗口
while True:
for event in pygame.event.get():
if event.type == MOUSEMOTION: # 监听鼠标移动事件
# 获取鼠标的坐标
mouseX, mouseY = pygame.mouse.get_pos()
# 设置图片的新位置为鼠标的坐标
imageRect = image.get_rect()
imageRect.centerx = mouseX
imageRect.centery = mouseY
# 清空屏幕
screen.fill((0, 0, 0))
# 在新位置绘制图片
screen.blit(image, imageRect)
# 刷新屏幕
pygame.display.flip()
pygame.quit()
这样,你就实现了鼠标控制图片移动的功能。希望这能帮到你!
MOUSEBUTTONDOWN只在鼠标按下时触发一次,而不会在长按时多次生成该事件。因此可以使用pg.mouse.get_pressed()方法,它将返回一个列表,包含当前每个鼠标按键的按下状况,如果按下则返回True。代码修改如下:
import pygame as pg
import sys
import time
pg.init() #初始化
screen = pg.display.set_mode((400, 400))
pg.display.set_caption("Pygame窗口")
image= pg.image.load("u=4269708609,317730862&fm=253&fmt=auto&app=138&f=JPEG.png")
image = pg.transform.scale(image,(25,25))
clock = pg.time.Clock()#控制FPS
background_color = (255, 255, 255)
while True:
screen.fill((background_color))
if pg.mouse.get_pressed()[0]: #按下左键
x, y = pg.mouse.get_pos()
x-= image.get_width() / 2
y-= image.get_height() / 2
screen.blit(image, (x, y))
else:
screen.blit(image, (0, 0))
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
sys.exit(0)
clock.tick(65)
pg.display.flip()
同时建议图片的命名不要过于随意,应进行修改使其更加具有描述性