0

im new to python and would like to move an image with the left mouse click, so far i have this:

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

but seem to getting a error:

'PhotoImage' object has no attribute 'collidepoint'

how would i be able to fix this?

Many thanks!

hiihihihelloo
  • 99
  • 2
  • 8

1 Answers1

0

As @Brian Ton comments above, you are trying to use pygame.rect methods on a tkinter.PhotoImage object.

If you want to get the mouse position on using Tkinter, this answer will help.

If you want to use pygame, here's an example that will draw a square where ever you click the mouse:

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()
import random
  • 3,054
  • 1
  • 17
  • 22