I'm trying to make a simple tkinter program where the character can "walk" through a forest. This is the code:
from tkinter import *; import random
root = Tk()
root.geometry(f"{root.winfo_screenwidth()}x{root.winfo_screenheight()}")
canvas = Canvas(root, bg="#052b05")
canvas.pack(fill="both", expand="True")
loading=canvas.create_text(root.winfo_screenwidth()/2,
root.winfo_screenheight()/2, text="loading, please wait...",
font=("calibri bold", 30), fill="white")
root.update()
x, y, xvel, yvel= 0,0,0,0
trees, basetreex, basetreey=[], [], []
for i in range(random.randint(5, 5)): # original: 50-150
treex=random.randint(-2000,2000) # original: -5000, 5000
treey=random.randint(-2000,2000) # original: -5000, 5000
treemodel=random.choice(["arbol1 krita.png", "arbol2 krita.png", "arbol3 krita.png"])
basetreex.append(treex); basetreey.append(treey)
Image=PhotoImage(file=treemodel)
Tree=canvas.create_image(treex+x, treey+y, image=Image)
trees.append(Tree)
canvas.create_oval(root.winfo_screenwidth()/2+20,root.winfo_screenheight()/2+20,
root.winfo_screenwidth()/2-20,root.winfo_screenheight()/2-20, fill="black")
canvas.delete(loading)
KeysPressed=[]
def NewKey(event):
global KeysPressed
if event.char not in KeysPressed:
KeysPressed.append(event.char)
def DelKey(event):
global KeysPressed
KeysPressed.pop(KeysPressed.index(event.char))
root.bind("<KeyPress>", NewKey) # key detection
root.bind("<KeyRelease>", DelKey)
while True:
#canvas.delete("all")
counter = 0
for tree in trees:
treeCoords = canvas.coords(tree)
treex, treey = treeCoords[0], treeCoords[1]
#if 1600 > treex + x > -200 and 1200 > treey + y > -200:
canvas.move(tree, treex-treex * 2, treey-treey * 2) # llevar el objeto a x0 y0
canvas.move(tree, x+basetreex[counter], y+basetreey[counter]) # cambiar x por x+basex
#print(basetreex[counter], basetreey[counter])
counter += 1
#print(x, y)
#try:
#print("coordenadas base x: ", basetreex[counter],"coordenadas base y: ", y+basetreey[counter], "contador: ", counter,
#"\n \n coordenadas en el canvas: ", canvas.coords(tree), "coordenadas del mundo: ", x, y)
#except:
# pass
if "w" in KeysPressed:
yvel += 1
if "s" in KeysPressed:
yvel -= 1
if "d" in KeysPressed:
xvel -= 1
if "a" in KeysPressed:
xvel += 1
x += xvel
y += yvel
xvel /= 1.02 # fricción
yvel /= 1.02
root.update()
my problem is that instead of the trees appearing in random places, they always appear in coordinates -2000, -2000, but when I print the coordinates of each object, they are all different. I've also tried printing the counter variable, and it works fine, so I guess I'm misusing canvas.move, but I have no idea. Is there any way to fix the code? Thanks in advance.
The problem is that the garbage collector is deleting the rest of your images (so you just create the object
Imagen = PhotoImage(file=treemodel)
and then overwrite it, it only keeps the lastPhotoImage
loaded one)The solution is to store it in a list, so that they are not deleted (I called it
imgmaster
)