如何通过点击移动图像?

How to move image with click?

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

但似乎出现错误:

'PhotoImage' object has no attribute 'collidepoint'

我该如何解决这个问题?

非常感谢!

正如上面的 @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()