-1

Win10 Python3.83

I hope that after clicking button, the corresponding message will pop up, but when this program runs, it is found that a message will be issued when the button is created, but there will be no message when clicked.How to solve it.

import tkinter as tk
import tkinter.messagebox as msg

def cbClicked(cbname):
    print(cbname)
    msg.showinfo('click', cbname)

cb_list = ['cmd1', 'cmd2', 'cmd3']
win = tk.Tk()

for inx, cbname in enumerate(cb_list):
    tk.Button(win, width=10, height=1, text=cbname, command = cbClicked(cbname)).grid(row=0, column=inx)

win.mainloop()

Emir-Liu
  • 68
  • 9
  • Change `command=cbClicked(cbname)` to `command=lambda name=cbname: cbClicked(name)`. – acw1668 Jun 19 '20 at 03:08
  • could you tell me how this works,or where to understand it – Emir-Liu Jun 19 '20 at 03:19
  • See [python-lambda-in-a-loop](https://stackoverflow.com/questions/19837486/python-lambda-in-a-loop) or [python-lambda-doesnt-remember-argument-in-for-loop](https://stackoverflow.com/questions/11723217/python-lambda-doesnt-remember-argument-in-for-loop). – acw1668 Jun 19 '20 at 04:39

1 Answers1

1

command option in tk.Button should be a function, not the result of function. You should pass the function name. At the same time, you need to pass argument, so define a lambda function for it.

Replace this line

tk.Button(win, width=10, height=1, text=cbname, command = cbClicked(cbname)).grid(row=0, column=inx)

with this

tk.Button(win, width=10, height=1, text=cbname, command = lambda x=cbname: cbClicked(x)).grid(row=0, column=inx)
Jason Yang
  • 11,284
  • 2
  • 9
  • 23