0

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.

0

2 Answers 2

2

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) ]
Sign up to request clarification or add additional context in comments.

3 Comments

to save space? memory? whats the advantage (other than it looks much better)?
@Thomas Kirkpatrick: to avoid repetition. Repeating yourself in code is often a sign that things could be done better.
@Thomas: Looking better is also a benefit. In this case though it's going to give you cleaner code.
0

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

1 Comment

dictionary! should have known that. works great, just construct a string and look it up. 'SqImg3':SqImg3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.