添加带有多个小部件链接的右键单击上下文菜单? [英] Adding a right click context menu with link with multiple widgets?
本文介绍了添加带有多个小部件链接的右键单击上下文菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的问题是这个问题
我想获得右键单击要对其执行操作的小部件。
I would like to get the widget which has been right clicked to do an action on it.
条件:
- 右键单击我的标签2
- 选择显示标签
预期结果:
=>应该打印我的标签2
=> "my label 2" should be printed
要解决的初始代码:
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()
推荐答案
对当前代码进行尽可能少的更改,您需要这三件事:
Making as few changes as possible to the current code, you need to do three things:
-
创建一个全局变量来保存对当前所选标签的引用。
Create a global variable to hold a reference to the currently selected label.
在 popup
内,将此变量设置为 event.widget
,将
Inside popup
, set this variable to event.widget
, which will be the currently selected label.
在 print_label
内,通过访问其<$ c $打印此标签的文本c>文本 键。
下面是程序的固定版本。我更改的内容在注释框中:
Below is a fixed version of your program. The stuff I changed is in the comment box:
from Tkinter import * # Tkinter -> tkinter in Python 3
root = Tk()
#############################################################
selected = None # This is the variable mentioned in step 1
def print_label():
print selected["text"] # This is step 3
def popup(event):
global selected # Tell Python that selected is global
menu.post(event.x_root, event.y_root)
selected = event.widget # This is step 2
#############################################################
# 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()
这篇关于添加带有多个小部件链接的右键单击上下文菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文