我是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'
我怎么能解决这个问题?
非常感谢!
答案 0 :(得分:0)
正如上面的@Brian Ton条评论,您尝试在pygame.rect
对象上使用tkinter.PhotoImage
方法。
如果你想使用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()