问题的简单示例
# import * is bad, this is just an example
from tkinter import *
root = Tk()
root.minsize(200, 200)
dict = {"1": ("banane 1", "fresh"), "2": ("banane 2", "not fresh"), "3": ("banane 3", "rotten")}
# Right click label
def openMenuGroup(self):
menuGroup.post(self.x_root, self.y_root)
def closeMenuGroup():
menuGroup.unpost()
menuGroup = Menu(root, tearoff=0)
for key, value in dict.items():
name, quality = value
lab = Label(text=name)
lab.quality = quality
lab.bind("<Button-3>", openMenuGroup)
lab.pack()
menuGroup.add_command(label="Check quality", command=lambda:checkQuality(lab.quality))
menuGroup.add_command(label="Close", command=closeMenuGroup())
def checkQuality(self):
print(self)
mainloop()
当您单击“检查质量”时,它将始终返回“烂”(最后一次迭代)。如何为每个标签获得正确的 lab.quality?
您需要在
openMenuGroup()
内创建弹出菜单,并将正确的质量传递给 checkQuality()
:
from tkinter import *
root = Tk()
root.minsize(200, 200)
dict = {"1": ("banane 1", "fresh"), "2": ("banane 2", "not fresh"), "3": ("banane 3", "rotten")}
def checkQuality(quality):
print(quality)
# Right click label
def openMenuGroup(event):
# create menu here
menuGroup = Menu(root, tearoff=0)
# use event.widget to reference the label that trigger this function
menuGroup.add_command(label="Check quality", command=lambda:checkQuality(event.widget.quality))
menuGroup.add_command(label="Close", command=menuGroup.unpost)
menuGroup.post(event.x_root, event.y_root)
for key, value in dict.items():
name, quality = value
lab = Label(text=name)
lab.quality = quality
lab.bind("<Button-3>", openMenuGroup)
lab.pack()
mainloop()