-1

I want to create a simple calculator with buttons from 1 to 9. I want to do that in two loops to be able to place them in a 3x3 square. But all buttons are returning the same value (9), and I can't figure out why. Anyone can help me with that? There is a code:

from tkinter import *

root = Tk()

e = Entry()
e.grid(row=0, column=0, columnspan=3)


def button_click(num):
    e.insert(0, num)


for i in range(1, 4):
    for j in range(0, 3):
        k = int(((i - 1) * 3) + (j + 1))
        button = Button(root, text=k, padx=25, pady=25, command=lambda: button_click(k))
        button.grid(row=i, column=j)
Demian Wolf
  • 1,698
  • 2
  • 14
  • 34

2 Answers2

1

This line is almost correct:

button = Button(root, text=k, padx=25, pady=25, command=lambda: button_click(k))

try:

button = Button(root, text=k, padx=25, pady=25, command=lambda k=k: button_click(k))
1

In addition to @Roei Duvdevani answer: you may also use functools.partial:

from functools import partial
from tkinter import *


root = Tk()

e = Entry()
e.grid(row=0, column=0, columnspan=3)


def button_click(num):
    e.insert(0, num)


for i in range(1, 4):
    for j in range(0, 3):
        k = int(((i - 1) * 3) + (j + 1))
        button = Button(root, text=k, padx=25, pady=25, command=partial(button_click, k))
        button.grid(row=i, column=j)

Here is more about functools.partial: https://www.geeksforgeeks.org/partial-functions-python/

And here is more information about your problem in general: Python Lambda in a loop

Demian Wolf
  • 1,698
  • 2
  • 14
  • 34