如何在python tkinter中右键单击将值传递给弹出命令 [英] how to pass values to popup command on right click in python tkinter

查看:58
本文介绍了如何在python tkinter中右键单击将值传递给弹出命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 gui,我在其中创建了一个带有几个选项的右键单击弹出菜单.现在我的查询是如何将一些变量或值或参数或字符串传递给包含在弹出菜单中的命令.我使用下面的代码来生成弹出菜单.

I am developing a gui in which i created a right click popup menu with few option. now my query is how can i pass some variables or values or argument or strings to the command incorporated in popup menu. i used below code to generate popup menu.

from Tkinter import *

root = Tk()

w = Label(root, text="Right-click to display menu", width=40, height=20)
w.pack()

# create a menu
popup = Menu(root, tearoff=0)
popup.add_command(label="Next", command=next(a,b))
popup.add_command(label="Previous")
popup.add_separator()
popup.add_command(label="Home")

def do_popup(event,a,b):
    # display the popup menu
    try:
        popup.tk_popup(event.x_root, event.y_root)
    finally:
        # make sure to release the grab (Tk 8.0a1 only)
        popup.grab_release()
def next(event,a,b):
    print a
    print b

w.bind("<Button-3>",lambda e, a=1, b=2: do_popup(e,a,b))

b = Button(root, text="Quit", command=root.destroy)
b.pack()

mainloop()

在上面的代码中,我想将 a 和 b 的值传递给 Next 命令.如何做到这一点.

I the above code i want to pass values of a and b to Next command. How to do that.

谢谢.

推荐答案

您需要存储这些值,以便在 next 事件处理程序中使用它们.您可以进行一些操作,例如使用 popup.values = (a, b) 在 Menu 对象中添加引用,但最简洁的方法是使用类来表示您的 GUI.

You need to store this values in order to use them in the next event handler. You can do some walkarounds, like adding a reference in the Menu object with popup.values = (a, b), but the cleanest way is to use classes to represent you GUI.

请注意,它就像子类化 Tkinter 小部件并添加要存储的值一样简单:

Note that it is as easy as subclassing Tkinter widgets, and adding the values you want to store:

from Tkinter import *

class App(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.a = 1
        self.b = 2
        self.label = Label(self, text="Right-click to display menu", width=40, height=20)
        self.button = Button(self, text="Quit", command=self.destroy)
        self.label.bind("<Button-3>", self.do_popup)
        self.label.pack()
        self.button.pack()
    def do_popup(self, event):
        popup = Popup(self, self.a, self.b)
        try:
            popup.tk_popup(event.x_root, event.y_root)
        finally:
            popup.grab_release()

class Popup(Menu):
    def __init__(self, master, a, b):
        Menu.__init__(self, master, tearoff=0)
        self.a = a
        self.b = b
        self.add_command(label="Next", command=self.next)
        self.add_command(label="Previous")
        self.add_separator()
        self.add_command(label="Home")
    def next(self):
        print self.a, self.b

app = App()
app.mainloop()

这篇关于如何在python tkinter中右键单击将值传递给弹出命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆