2

オプションの少ない右クリックポップアップメニューを作成したGUIを開発しています。今、私の質問は、ポップアップメニューに組み込まれたコマンドに変数、値、引数、または文字列を渡す方法です。以下のコードを使用してポップアップメニューを生成しました。

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 コマンドに渡したいと考えています。どうやってするか。

ありがとう。

4

2 に答える 2

3

nextイベントハンドラで使用するには、この値を保存する必要があります。を使用してMenuオブジェクトに参照を追加するなど、いくつかのウォークアラウンドを実行できますpopup.values = (a, b)が、最もクリーンな方法は、クラスを使用してGUIを表すことです。

Tkinterウィジェットをサブクラス化し、保存したい値を追加するのと同じくらい簡単であることに注意してください。

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()
于 2013-03-17T18:40:14.577 に答える