How to find out which button is clicked when creating multiple buttons in loop? #1169
-
QuestionHi All, I am importing an excel file, and then creating buttons for each sheet. Idea is that they will click the button and then they can see the sheet data. I can do this for a single button, by manually specifying the sheet name. Ex: like this data = pd.read_excel('test_excel.xlsm', sheet_name=None)
sh = list(data.keys())[4] # Taking a random sheet for example
ui.button(sh,on_click=lambda: show_data())
def show_data():
df = media_data[sh]
ui.table(
columns=[{'name': col, 'label': col, 'field': col} for col in df.columns],
rows=df.to_dict('records'),
) But how do I convert this into a loop and do it for all sheets? I tried something like this below: with ui.row():
for sh, df in data.items():
ui.button(sh, on_click=lambda: show_data()) But the problem I understood is that because this is a loop, the final value of How do I write the Kindly let me know what would be right way to approach this please. Many thanks for all the help. Thanks, |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
You'd better put the parameter in callback. Like this: table = ui.table(rows=[], columns=[])
def show_data(sh):
df = media_data[sh]
table.rows[:] = df.to_dict('records')
table.update()
with ui.row():
for sh, df in data.items():
ui.button(sh, on_click=lambda: show_data(sh)) |
Beta Was this translation helpful? Give feedback.
Apart from that there's an issue with Python's "late binding":
Try
vs.
The
i=i
captures thei
within the lambda statement. When the lambda is eventually evaluated, it would use the current value ofi
(which is now 3). But withi=i
the label is created using a local copy.