如何用点击移动图像?

2024-04-19 21:45:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我想用鼠标左键移动图像,到目前为止,我有这个:

from tkinter import *
import pygame

root = Tk()

def callback(event):

  if new.collidepoint(mouseposition):
        canvas.move(new, 60,30)


  canvas= Canvas(root, width=500, height=500)
  canvas.pack(expand = YES, fill = BOTH)

  new = PhotoImage(file = 'C:\\Users\\Andy\\Documents\\all pc 
  stuff\\Python\\CarPic.png')
  canvas.create_image(50,10,image=new, anchor=NW)
  canvas.bind("<Button-1>", callback)
  canvas.pack()

  root.mainloop()

但似乎有一个错误:

^{pr2}$

我怎样才能解决这个问题?在

非常感谢!在


Tags: from图像imageimportnewtkintercallbackroot
1条回答
网友
1楼 · 发布于 2024-04-19 21:45:16

正如上面的@Brian Ton注释,您正试图在tkinter.PhotoImage对象上使用pygame.rect方法。在

如果您想在使用Tkinter时获得鼠标位置,this answer将有所帮助。在

如果你想使用pygame,这里有一个例子,在你点击鼠标的地方画一个正方形:

import pygame

pygame.init()
screen_width, screen_height = 640, 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Click Move Demo')
clock = pygame.time.Clock() #for limiting FPS
FPS = 30
exit_demo = False
# start with a white background
screen.fill(pygame.Color("white"))
# instead of loading an image, draw one
img = pygame.Surface([20, 20])
img.fill(pygame.color.Color("turquoise"))
width, height = img.get_size()
# draw the image in the middle of the screen
pos = (screen_width // 2, screen_height // 2)  
# main loop
while not exit_demo:
    for event in pygame.event.get():            
        if event.type == pygame.QUIT:
            exit_demo = True
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                # fill the screen with white, erasing everything
                screen.fill(pygame.Color("white"))
        elif event.type == pygame.MOUSEBUTTONUP:
            if event.button == 1:  # left
                pos = (event.pos[0] - width, event.pos[1] - height)                   
            elif event.button == 2: # middle
                pos = (event.pos[0] - width // 2, event.pos[1] - height // 2)
            elif event.button == 3: # right
                pos = event.pos
            elif event.button == 4:  # wheel up
                pos = (pos[0], pos[1] - height)  # move from stored position
            elif event.button == 5:  # wheel down
                pos = (pos[0], pos[1] + height)

    # draw the image here
    screen.blit(img, pos)
    # update screen
    pygame.display.update()
    clock.tick(FPS)
pygame.quit()
quit()

相关问题 更多 >