Hello so I've been trying to solve this problem but cant find anything I tried dictionaries and exec. How can I use string value as a variable name? I have a problem when I define a variable name in a string and try to make a button with the image it shows error - _tkinter.TclError: image "score6" doesn't exist, but if I manually type in the image variable name the error doesn't show.
img = 'score' str(correct) #here I make the variable name #the scores can be from 0-9
self.rez = Button(window, relief="sunken", image=img, bd=0, bg='#cecece',activebackground='#cecece')
self.rez.place(x=520, y=330)
#this is where images are defined(this is outside the class)
score0 = ImageTk.PhotoImage(Image.open("scores/09.png"))
score1 = ImageTk.PhotoImage(Image.open("scores/19.png"))
score2 = ImageTk.PhotoImage(Image.open("scores/29.png"))
score3 = ImageTk.PhotoImage(Image.open("scores/39.png"))
score4 = ImageTk.PhotoImage(Image.open("scores/49.png"))
score5 = ImageTk.PhotoImage(Image.open("scores/59.png"))
so how can I use string value as a variable name?
CodePudding user response:
You could do this using eval
img = eval('score' str(correct))
but this is dangerous if correct
is provided by the user. A better approach is to use a list
images = [ImageTk.PhotoImage(Image.open("scores/09.png")),
ImageTk.PhotoImage(Image.open("scores/19.png")),
ImageTk.PhotoImage(Image.open("scores/29.png")),
ImageTk.PhotoImage(Image.open("scores/39.png")),
ImageTk.PhotoImage(Image.open("scores/49.png")),
ImageTk.PhotoImage(Image.open("scores/59.png"))]
img = images[correct]
CodePudding user response:
Firstly, you'll probably want to import Pathlib
to work with the absolute paths to your image files
from pathlib import Path
Then I think it might make more sense to put your image filenames into a list...
image_dir = Path(r'C:\<path>\<to>\scores') # the folder containing the images
images = [ # list of individual image file names
"09.png",
"19.png",
"29.png",
"39.png",
"49.png",
"59.png",
...
] # etc.
And then define a function that can handle fetching these images as needed
def set_image(correct): # I assume 'correct' is an integer
img = ImageTk.PhotoImage(
Image.open(
# open the correct image (-1 to accommodate zero-indexing)
image_dir.joinpath(images[correct - 1])
)
)
return img
Then you can update your button's image like so, for example:
self.rez.configure(image=img)