Reputation: 13
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)
Upvotes: 1
Views: 1206
Reputation: 142651
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).
Upvotes: 1
Reputation: 121
With variables used inside of a function, you have to return them. For example:
a = 5
b = 6
def func(a,b):
a += 5
b += 5
return a
a = func(a,b)
print(a) #10
print(b) #6, not 11
It doesn't change the variable inside the function, so you must return the variable and reassign it, like I did with a
. b
won't change unless you reassign it to the function value.
If you need to return multiple values:
return [a, b]
f = func(a, b)
a, b = f[0], f[1]
Upvotes: 0