python 3 variable used in another variable's name?
in python 3 (with tkinter) i have the following images:
SqImg1 = PhotoImage(file='SqImg1.gif')
SqImg2 = PhotoImage(file='SqImg2.gif')
SqImg3 = PhotoImage(file='SqImg3.gif开发者_如何转开发')
SqImg4 = PhotoImage(file='SqImg4.gif')
...
i also have a function that needs to return one of those images based on a variable. so if the function determines var to be 1, it needs to return SqImg1...
def returnImage():
list = ['ale', 'boo', 'boo', 'cat', 'doe', 'boo', 'eel']
var = 0
for item in list:
if item == 'boo':
var += 1
return SqImg[var]
i would want the above to return SqImg3
this is probably simple, but i can't seem to find what im looking for with google.
There's your mistake straight away:
SqImg1 = PhotoImage(file='SqImg1.gif')
SqImg2 = PhotoImage(file='SqImg2.gif')
SqImg3 = PhotoImage(file='SqImg3.gif')
SqImg4 = PhotoImage(file='SqImg4.gif')
...
should be:
SqImg = [
PhotoImage(file='SqImg1.gif'),
PhotoImage(file='SqImg2.gif'),
PhotoImage(file='SqImg3.gif'),
PhotoImage(file='SqImg4.gif'),
...
]
or even:
SqImg = [ PhotoImage(file='SqImg{}.gif'.format(i) for i in range(1, n) ]
Two options
- Create a dictionary and map the strings to the actual variables. E.g.,
d = {}; d["boo"] = img3
- Call eval() if your images are numbered correctly.. e.g.,
return eval("sqlimg%d" % var)
The first option is probably what you're looking for unless you have special circumstances
精彩评论