首页 > 解决方案 > 我需要从数组中提取图像文件名的文本,但只得到“pyimage#”或“tkinter.PhotoImage object at X”作为回复

问题描述

我正在尝试创建一个数组,其中包含各种不同的随机图像文件,以显示在 Tkinter 中的一组按钮上。单击给定按钮时,我想将该文件名的文本添加到新数组中。基本上,当单击带有 imageX 的按钮时,将“imageX”添加到新数组中。

不幸的是,我总是得到一个不是图像文件名的返回值,也不是我设置为对应于该图像的变量,而是:

我觉得应该有一种简单的方法来做到这一点,我已经尝试了我能想到的所有工作,但我没有让它发挥作用。任何帮助将不胜感激!谢谢!

这是相关代码的缩短/简化版本:

master=tkinter.Tk()
master.title("Not working")

a1b1c1 = PhotoImage(file = r"C:/users/jdavis319/documents/bushesoflove/BoLdraw/a1b1c1.png")
a1b1c2 = PhotoImage(file = r"C:/users/jdavis319/documents/bushesoflove/BoLdraw/a1b1c2.png")
a1b1c3 = PhotoImage(file = r"C:/users/jdavis319/documents/bushesoflove/BoLdraw/a1b1c3.png")
a1b2c1 = PhotoImage(file = r"C:/users/jdavis319/documents/bushesoflove/BoLdraw/a1b2c1.png")
a1b2c2 = PhotoImage(file = r"C:/users/jdavis319/documents/bushesoflove/BoLdraw/a1b2c2.png")

population = [a1b1c1, a1b1c2, a1b1c3, a1b2c1, a1b2c2]

populationbeta = []

populationbeta.append(population[0])

print(populationbeta)

这给出了结果:“[<tkinter.PhotoImage object at 0x000001A419D4F070>]”

标签: arraysimagevariablestkinterfilenames

解决方案


这给出了结果:“[<tkinter.PhotoImage object at 0x000001A419D4F070>]”

正确的。这表明您有一个PhotoImage对象列表。如果您想要可以.cget('file')在对象上使用的文件名。cget是获取配置选项值的常用 tkinter 方法。

filenames = [image.cget('filename') for image in population]

或者,如果您不想使用列表推导来创建文件名列表,您可以对单个图像执行此操作,如下所示:

populationbeta.append(population[0].cget("file"))

推荐阅读