【发布时间】:2018-10-10 00:58:54
【问题描述】:
我在 Python 3.7 中编写了这段代码
from tkinter import *
root = Tk()
import random
def cmd():
print("Files:", img1.cget("file"), img2.cget("file"))
img = random.choice([img1, img2])
can.itemconfig(log, image=img)
print("Choice:", can.itemcget(log, "image"))
img1 = PhotoImage(file="a.gif")
img2 = PhotoImage(file="b.gif")
can = Canvas(root, width=300, height=300, bg="white")
log = can.create_image(151, 151, image=None)
can.pack()
btt = Button(root, text="click", command=cmd)
btt.pack()
root.mainloop()
我想打印画布中配置的图像名称
print("Files:", img1.cget("file"), img2.cget("file"))
Result > Files: a.gif b.gif < Return Filename OK
print("Choice:", can.itemcget(log, "image"))
Result > Choice: pyimage1 Or Choice: pyimage2 < Return String No OK
我该怎么办?谢谢!
【问题讨论】:
-
img.cget('file')有什么问题。或者只是保留一个参考? -
第一个打印显示可能出现的选择,第二个打印必须显示代码返回的随机选择
-
您需要单独存储所选图像的名称。 Canvas 图像项不需要该信息,因此不会将其存储在任何地方。
-
感谢 jasonharper 的回答,如果 print ("Choice:", can.itemcget (log, "image")) 返回 pyimage1 等。作为字符串,我可以通过 PhotoImage 获取图像名称吗这些字符串的结果?
标签: python-3.x tkinter