我有一个静态的工作示例,该示例显示垂直对齐的图像,并在单击时打印提供的appName(img1-3)。 当我遍历图像列表时,可以显示垂直对齐的图像,但是单击任何图像都会打印“ pyimag3”而不是“ pyimage1-3”?
静态示例(确定):
import Tkinter as tk
import ttk
import os
root = tk.Tk()
root.resizable(width=False, height=False)
root.geometry("500x500")
root.config(bg="green")
iconPath = os.path.dirname(os.path.abspath(__file__))
#create container
body_frame = tk.Frame(root)
body_frame.pack()
def appName(imgx):
print imgx
imgs = tk.PhotoImage(file = iconPath + '\\icons\\img1.gif')
imgs2 = tk.PhotoImage(file = iconPath + '\\icons\\img2.gif')
imgs3 = tk.PhotoImage(file = iconPath + '\\icons\\img3.gif')
appIcon = tk.Label(body_frame, image=imgs)
appIcon.bind("<Button-1>", lambda x: appName('img1'))
appIcon.grid(row=1, column=1)
appIcon = tk.Label(body_frame, image=imgs2)
appIcon.bind("<Button-1>", lambda x: appName('img2'))
appIcon.grid(row=2, column=1)
appIcon = tk.Label(body_frame, image=imgs3)
appIcon.bind("<Button-1>", lambda x: appName('img3'))
appIcon.grid(row=3, column=1)
root.mainloop()
for循环(问题):
import Tkinter as tk
import ttk
import os
root = tk.Tk()
root.resizable(width=False, height=False)
root.geometry("500x500")
root.config(bg="green")
iconPath = os.path.dirname(os.path.abspath(__file__))
#create container
body_frame = tk.Frame(root)
body_frame.pack()
def appName(imgx):
print imgx
imgList = ['img1.gif', 'img2.gif', 'img3.gif']
rowCount = 0
for item in imgList:
imgs = tk.PhotoImage(file = iconPath + '\\icons\\'+imgList[rowCount])
photo = tk.Label(body_frame, image=imgs)
photo.image = imgs
photo.bind("<Button-1>", lambda x: appName(imgs))
photo.grid(row=rowCount, column=1)
rowCount = rowCount+1
root.mainloop()