0

I am working on a Choose-Your-Own-Adventure game in Python. Every so often, I want the user to be given a scene, and be allowed to find objects in that scene. Whatever they find can be put in their inventory, and whenever they are ready to stop looking for items, they can hit an "Exit" button in the bottom left. However, I am running into some errors with actually getting the button click coordinates to actually do something.

So far, I have this:

root = Tk()
imageIQ1 = Canvas(root, width=1000, height=1000)
imageIQ1.pack()
original = Image.open("prison.jpg")
original = original.resize((1000,1000)) #resize image
img = ImageTk.PhotoImage(original)
imageIQ1.create_image(0, 0, image=img, anchor="nw")

def getcoors(eventcoors):
    global x0,y0
    x0 = evencoors.x
    y0 = evencoors.y
    print(x0,y0)

After the user clicks a certain set of coordinates (or somewhere near them), I want the program to clear the picture from the screen and continue with the program. For insance, clicking anywhere from (300, 400) to (500, 500) would close the picture and continue with the rest of the program. I know this will use some form of loop like

while (x not in range) and (y not in range):

But I am unsure of what I would actually do to clear the image. I read about using something like .kill() and .terminate(), but they don't work in this situation.

Any ideas?

HunBurry
  • 113
  • 14

1 Answers1

1

You need to have a reference for the image in order to later be able to delete it as in:

canvImg = imageIQ1.create_image(0, 0, image=img, anchor="nw")

and then when you call:

imageIQ1.delete(canvImg)

it will get deleted.


Based on this you can put that in an event method like:

def motion(event):
    x, y = event.x, event.y

    someSpecificX = 142
    someSpecificY = 53
    marginX = 100
    marginY = 100
    print(x, y)

    if x in range(someSpecificX - marginX, someSpecificX + marginX):
        if y in range(someSpecificY - marginY, someSpecificY + marginY):
            imageIQ1.delete(canvImg)

imageIQ1.bind('<Button-1>', motion)

Your final code should look like:

from tkinter import *
from PIL import ImageTk, Image

root = Tk()
imageIQ1 = Canvas(root, width=1000, height=1000)
imageIQ1.pack()
original = Image.open("prison.jpg")
original = original.resize((1000,1000)) #resize image
img = ImageTk.PhotoImage(original)
canvImg = imageIQ1.create_image(0, 0, image=img, anchor="nw")

def motion(event):
    x, y = event.x, event.y

    someSpecificX = 142
    someSpecificY = 53
    marginX = 100
    marginY = 100
    print(x, y)

    if x in range(someSpecificX - marginX, someSpecificX + marginX):
        if y in range(someSpecificY - marginY, someSpecificY + marginY):
            imageIQ1.delete(canvImg)


imageIQ1.bind('<Button-1>', motion)

root.mainloop()
Nae
  • 14,209
  • 7
  • 52
  • 79
  • maybe create example with [tag_bind()](http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.tag_bind-method) – furas Dec 01 '17 at 18:53