【问题标题】:_tkinter.TclError: image "score6" doesn't exist_tkinter.TclError:图像“score6”不存在
【发布时间】:2022-12-03 14:22:50
【问题描述】:

你好,所以我一直在努力解决这个问题,但我试过字典和 exec 找不到任何东西。如何使用字符串值作为变量名?当我在字符串中定义变量名称并尝试使用显示错误的图像创建按钮时出现问题 - _tkinter.TclError:图像“score6”不存在,但如果我手动输入图像变量名称错误不显示。

 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) 

#这是定义图像的地方(这是在类之外)

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?

【问题讨论】:

标签: python tkinter


【解决方案1】:

你可以使用eval来做到这一点

img = eval('score' + str(correct))

但如果用户提供correct,这是很危险的。更好的方法是使用列表

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]

【讨论】:

    【解决方案2】:

    首先,您可能希望导入 Pathlib 以使用图像文件的绝对路径

    from pathlib import Path
    

    然后我认为将您的图像文件名放入列表中可能更有意义......

    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.
    

    然后定义一个可以根据需要处理获取这些图像的函数

    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
    

    然后您可以像这样更新按钮的图像,例如:

    self.rez.configure(image=img)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-12
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多