Question

when the user score is changed directly to the image name, the program displays the correct image. however when it is stored in a variable it seems to be unable to find the image, even though it prints the correct image name.

import tkinter as tk

window = tk.Tk()
canvas = tk.Canvas(window, width = 400, height = 200, bg = 'white')

_1 = tk.PhotoImage(file= '1.gif')

score = 1
score = str(score)
user_score = '_' + score
print(user_score)
canvas.create_image((200,100), image=user_score)

canvas.pack()
canvas.update()
window.mainloop()

it errors saying image "_1" does not exist when _1 is what the image is stored as. could someone pleas show me how to fix this. Cheers

Was it helpful?

Solution

An alternative to the eval() method suggested by @Ashok would be to access the image through a dictionary that has scores as keys and image instances as values. I assume the reason you don't pass the variable for the image instance directly is because score can change. If you know the scores beforehand, you can use a method similar to this:

images = {
    '_1': tk.PhotoImage(file='1.gif'), # score is key, image instance is value
    '_2': tk.PhotoImage(file='2.gif'),
    '_3': tk.PhotoImage(file='3.gif')
    }

score = 1
score = str(score)
user_score = '_' + score
print(user_score)

# set the image to the corresponding dict key
canvas.create_image((200,100), image=images[user_score])

You can also implement error handling (if score is 4) to handle KeyErrors, and display a default image or none at all.

OTHER TIPS

Hey looks like you are using a string type to represent an image. An 'instance' should represent the image.

Using "canvas.create_image((200, 100), image = eval(user_score))" in the script should solve the issue

import tkinter as tk
window = tk.Tk()
canvas = tk.Canvas(window, width = 800, height = 1000, bg = 'white')
_1 = tk.PhotoImage(file= '1.gif')
print type(_1) #This should be an instance i.e here its a tkinter photoimage
score = 1
score = str(score)
user_score = '_' + score
print user_score
print type(user_score) #This should be a string
canvas.create_image((200, 100), image = eval(user_score))
canvas.pack()
canvas.update()
window.mainloop()

#The output of this program should look something like below:
<type 'instance'>
_1
<type 'str'>
And Python tkinter should display a canvas with the image specified

Using eval(string) should evaluate the value of the string defined. But we should need to be cautious using the eval() function since it blindly evaluates the entire string irrespective of the actual validation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top