Search code examples
pythontkintercanvastags

tkinter canvas can't seem to create a tag within a function


Making a basic game using tkinter only. I can use a tag in my main program fine, but when I create one in my function I'm ignored. Below is the problem part of the code. The alienship tag works fine. The tag is saved and is usable. But for the line create inside the function, no matter how I assign the tag, it isn't saved. I've tried tag/tags/string instead of a variable/itemconfig/using bob=/master.bob=

I'm out of ideas.

from tkinter import *
import random

master = Tk()
w = Canvas(master, width=600, height=800,bg='black')
w. pack()

bang = 0        #check if there's a shot active
shottag = "1"
alientag = "a"

def control(event):
    global bang,shottag

    key = event.keycode
    if key == 38:                 #up arrow
        if bang<3:
            bang=bang+1
            shottag=shottag+"1"
            xy = w.coords(ship)
            w.create_line(xy[0],700,xy[0],730,fill="white",width=3,tag=shottag)
          # w.coords(shottag) would produce [] here -- i.e. no coords

shippic = PhotoImage(file = "ship.gif")
ship = w.create_image(300, 750, anchor=CENTER, image=shippic)

aliens = PhotoImage(file = "head.gif")
w.create_image(random.randint(40,560), 40, anchor=CENTER, image=aliens, tag=alientag)
  
w.after(100,moveals,alientag)
# this tag works fine

master.bind('<Key>',control)

Solution

  • You created a tag which has only numbers so it looks like "item handle" so it's not treated as tag.

    Use char in tag - ie. shottag = "s" - and it will work.


    From effbot.org The Tkinter Canvas Widget:

    Tags are symbolic names attached to items. Tags are ordinary strings, and they can contain anything except whitespace (as long as they don’t look like item handles).