How to pass arguments to a Button command in Tkinter? Ask Question

How to pass arguments to a Button command in Tkinter? Ask Question

Suppose I have the following Button made with Tkinter in Python:

import Tkinter as Tk
win = Tk.Toplevel()
frame = Tk.Frame(master=win).grid(row=1, column=1)
button = Tk.Button(master=frame, text='press', command=action)

The method action is called when I press the button, but what if I wanted to pass some arguments to the method action?

I have tried with the following code:

button = Tk.Button(master=frame, text='press', command=action(someNumber))

This just invokes the method immediately, and pressing the button does nothing.


See Python Argument Binders for standard techniques (not Tkinter-specific) for solving the problem. Working with callbacks in Tkinter (or other GUI frameworks) has some special considerations because the return value from the callback is useless.

ループ内で複数のボタンを作成し、ループ カウンターに基づいてそれぞれに異なる引数を渡すと、遅延バインディングと呼ばれる問題が発生する可能性があります。詳細については、「tkinter で for ループ内でコマンド引数を渡すボタンを作成する」を参照してください。

ベストアンサー1

これは、次のように を使用して実行できますlambda

button = Tk.Button(master=frame, text='press', command= lambda: action(someNumber))

これは、明示的なラッパー メソッドを使用せずに、または元の を変更せずに引数をバインドする簡単な方法ですaction

おすすめ記事