Domko
Domko

Reputation: 1

How do I make the pictures not disappear when a new one is created?

This is my code for it the froggy.png is a picture I have saved that i want to use as a something i can click for a game that I'm working on

from tkinter import *
import tkinter
import random
from PIL import Image, ImageTk

from functools import partial
width1=1280
height1=720
canvas = tkinter.Canvas(width=width1,height=height1, bg = 'white')
canvas.pack()

def clicked(*args):
    label.destroy()

def square():
    global label
    global img
    sq_time = random.randrange(4000,6000)
    x = random.randrange(100,width1-40,40)
    y = random.randrange(40,height1-40,40)
    img  = ImageTk.PhotoImage(Image.open('froggy.png'))
    label = Label(canvas, image = img)
    label.place(x = x , y = y)
    label.bind("<Button-1>",partial(clicked))
    canvas.after(sq_time, square)
square()
mainloop()

Upvotes: 0

Views: 129

Answers (1)

Сергей Кох
Сергей Кох

Reputation: 1723

So the pictures don't disappear, but

from tkinter import *
import random
from PIL import Image, ImageTk

from functools import partial

width1 = 1280
height1 = 720


def clicked(*args):
    label.destroy()


def square():
    global label
    global img
    sq_time = random.randrange(4000, 6000)
    x = random.randrange(100, width1 - 40, 40)
    y = random.randrange(40, height1 - 40, 40)

    label = Label(canvas, image=img)
    label.place(x=x, y=y)
    label.bind("<Button-1>", partial(clicked))
    root.after(sq_time, square)


root = Tk()
canvas = Canvas(root, width=width1, height=height1, bg='white')
canvas.pack()
img = ImageTk.PhotoImage(Image.open('froggy.png'))
square()
root.mainloop()

now you need to collect all the labels in a list and then look at which label was clicked to remove it.

Upvotes: 1

Related Questions