MissSprezzatura
MissSprezzatura

Reputation: 313

Change the text of an existing text item without having to create new text items? Tkinter

So I asked a similar question before but I didn't really get any replies so this is a follow up question on a comment... The code is below and I have no idea how to stop the text from over lapping each other, I tried to delete it before creating a new text but then it just returns an error about coordinates not being correct so I doubt that's the solution. Could someone please help?

fuel = 20
# What happens when you click the space bar
def space(evt):
   # Creates text that tells you the velocity and decreases velocity
   global vy, g, dt, fuel
   f=('Times',36,'bold')
   txt=canvas.create_text(w-100,50,
   text=str(fuel),font=f,fill='white')
   if(fuel<0): return
   fuel -= 1
   canvas.delete(txt)
   canvas.create_text(txt, text=str(fuel))
   vy -= 3*g*dt    
# If space key pressed, the function space happens
root.bind('<space>',space)

Thank you!!

Upvotes: 0

Views: 1521

Answers (1)

Lafexlos
Lafexlos

Reputation: 7735

In your method, you are creating text twice.

After your first call, there is already a text item created by

canvas.create_text(txt, text=str(fuel))

If space method gets called again, you will create an extra one and this will keep going on for each call.

Instead of delete-create text everytime, you can create a single text item in global scope then change its text value using canvas.itemconfig() method.

txt=canvas.create_text(w-100, 50, text=str(fuel), font=f, fill='white')
def space(evt):
    ...
    ...
    canvas.itemconfig(txt, text=str(fuel))

Upvotes: 4

Related Questions