我的问题是一个类似于这个问题的后续:这个问题。我希望在右键单击小部件时对其执行操作。
条件:
- 右键单击“我的标签2”
- 选择“显示标签”
=> “my label 2”应该被打印出来
初始代码:from Tkinter import * # Tkinter -> tkinter in Python 3
root = Tk()
def print_label():
print "Please, help me to print the label which has been clicked !"
def popup(event):
menu.post(event.x_root, event.y_root)
# create a popup menu
menu = Menu(root, tearoff=0)
menu.add_command(label="Display the label", command=print_label)
# create the 3 labels
label1_text=StringVar()
label2_text=StringVar()
label3_text=StringVar()
label1_text.set("my label 1")
label2_text.set("my label 2")
label3_text.set("my label 3")
label1=Label(root, textvariable=label1_text)
label2=Label(root, textvariable=label2_text)
label3=Label(root, textvariable=label3_text)
label1.pack()
label2.pack()
label3.pack()
# attach popup to frame
label1.bind("<Button-3>", popup)
label2.bind("<Button-3>", popup)
label3.bind("<Button-3>", popup)
root.mainloop()