Jeremy Darrach
Jeremy Darrach

Reputation: 263

Tkinter: move to random position on click

I'm working on a simple tkinter game, and have run into a problem. I want to be able to move an image to a random spot on the screen when you click on it, but what I thought would work hasn't. Below is the code:

spr_earth=PhotoImage(file="earth.gif")
x=r.randrange(64,roomw-64)
y=r.randrange(64,roomh-64)

earth=canvas.create_image(x,y,image=spr_earth)
x1,x2,y1,y2=canvas.bbox(earth)


def click(event):
if ((event.x>x1) and (event.x<x2)) and ((event.y>y1) and (event.y<y2)):
    canvas.move(earth,r.randrange(64,roomw-64),r.randrange(64,roomh-64))

root.bind_all("<Button-1>",click)
root.mainloop()

I thought this would work, but it clearly doesn't. You can click on it, but it appears to teleport into space an beyond :)

I'd appreciate anyone's input on this problem. thanks

Upvotes: 1

Views: 2439

Answers (1)

mgilson
mgilson

Reputation: 309861

From reading the documentation, it looks like move coordinates are relative to the current position.

Perhaps something like this would work (warning, this code is untested):

def click(event):
    if ((event.x>x1) and (event.x<x2)) and ((event.y>y1) and (event.y<y2)):
        canvas.coords(earth,(r.randrange(64,roomw-64),r.randrange(64,roomh-64)))

for what it's worth, the following simplified script seemed to work for me:

import Tkinter as tk
from random import randrange

root = tk.Tk()
canvas = tk.Canvas(root,width=400,height=400)
canvas.pack()
image = tk.PhotoImage(file='mouse.gif')

def position():
    return randrange(0,400),randrange(0,400)

mouse = canvas.create_image(*position(),image=image)

def click(event):
    canvas.coords(mouse,position())

canvas.bind('<Button-1>',click)

root.mainloop()

(The mouse always stayed partially on the canvas).

enter image description here

Upvotes: 2

Related Questions