Tkinter Button Command switches when new Button is used [duplicate]

141
April 13, 2022, at 7:00 PM
This question already has an answer here:
How to understand closure in a lambda? (1 answer)
Closed 2 months ago.

I face an issue which is that my first button is using the second button's command. I have faced this logic error multiple times when trying to create buttons programmatically with different functions, is there a way to resolve this or is this a limitation to Tkinter? The gif below illustrates my issue.

import tkinter as tk
root = tk.Tk()
root.geometry("400x400")
def print_when_clicked(message):
    print(message)
array = ["hi", "bye"]
for i in array:
    tk.Button(root, text=i, command=lambda:print_when_clicked(i)).pack()

Answer 1

You have fallen in to one of the classic Python traps. The issue is that the lambda captures the i variable, NOT the value of i. So, after the loop finishes, i is bound to "bye", and both functions use it.

The trick to work around this is to use a fake default argument:

for i in array:
    tk.Button(root, text=i, command=lambda i=i:print_when_clicked(i)).pack()
Rent Charter Buses Company
READ ALSO
Updating a node with merge using Py2Neo

Updating a node with merge using Py2Neo

I'm trying to merge and then update a graph using the py2neo libraryMy code looks roughly like

94
Replacing numerical IDs contained as lists of strings and lists of ints in a Pandas DataFrame

Replacing numerical IDs contained as lists of strings and lists of ints in a Pandas DataFrame

In order to make data anonymous, I need to replace original IDs with a different set of new IDs, but still have identical original IDs match across all fields after being replacedThe challenge is doing so elegantly across 4 different presentations of IDs in this Pandas...

131
How to compress pandas dataframe

How to compress pandas dataframe

Below I am showing few entries of my dataframeMy (each) dataframe has millions row

128
How to make a custom python class to support memoryview conversion

How to make a custom python class to support memoryview conversion

Is it possible for a custom class to implement memoryview(obj)?

89