添加带有多个小部件链接的右键单击上下文菜单?

时间:2014-05-23 17:26:17

标签: python user-interface tkinter contextmenu

我的问题是对this question

的一种跟进

我想获取右键单击的小部件对其执行操作。

条件:

  1. 右键点击“我的标签2”
  2. 选择“显示标签”
  3. 预期结果:

    =>应该打印“我的标签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()
    

1 个答案:

答案 0 :(得分:2)

对当前代码进行尽可能少的更改,您需要做三件事:

  1. 创建一个全局变量来保存对当前所选标签的引用。

  2. popup内,将此变量设置为event.widget,这将是当前选定的标签。

  3. print_label内,通过访问其"text"键打印此标签的文字。

  4. 以下是您的程序的固定版本。我更改的内容在评论框中:

    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()