How to pass arguments to a Button command in Tkinter?

原本只有使用英文的介面來設計GUI,遇到完成按鈕的處理後,需要顯示提示訊息,但每次都重新到畫面中取得目前操作中的語言,似乎有點太慢,所以希望在按下button 時,順便把操作時的語系代碼傳入給 command.


btna = Button(root, text = 'ButtonA', command = my_command)


def btn_restore_defaults_clicked(language_code):
btn_restore_defaults = ttk.Button(frame_action, text=translate[language_code]['restore_defaults'], command= lambda: btn_restore_defaults_clicked(language_code))

使用起來,很簡單,加一個 lambda: 就結束了。


I personally prefer to use lambdas in such a scenario, because imo it’s clearer and simpler and also doesn’t force you to write lots of wrapper methods if you don’t have control over the called method, but that’s certainly a matter of taste.

That’s how you’d do it with a lambda (note there’s also some implementation of currying in the functional module, so you can use that too):

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


發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *