-1
class Calc:
    def __init__(self):
        ls = ("1", "2", "3", "4", "5", "6", "7", "8", "9", "-", "+", "/", "x", "=", "a", ".")
        column = 5
        row = 5
        count = 2

        for x in ls:
            bt=Button(root, text=x, command="")


            for y in x:

                bt.grid(row=(row), column=(column))
                column = column + 1
                count = count + 1
                if count> row:
                    column = column-4
                    row = row +4


cal=Calc()

Above is my code. My question is how can I call a function so that the button pressed, for instance button 1, prints 1 into the console. Only seem to be able to print the whole list of 1, 16 buttons or I can print the very last position in the list which is ".". I can't print 1 or 2 or 3 etc?

j_4321
  • 15,431
  • 3
  • 34
  • 61
Nick
  • 81
  • 1
  • 1
  • 5

1 Answers1

1

You can use lambda to assign function with parameter.

If you use lambda in for you have to use char=item in lambda

command=lambda char=item:self.on_press(char)

because when you use lambda:self.on_press(item) then it use reference to item, not value from item. And it will get value from item when you press button but after for loop you have last value from list and all button get the same value.

Full code

import tkinter as tk    

class Calc:

    def __init__(self, master):
        ls = (
            ("1", "2", "3"),
            ("4", "5", "6"),
            ("7", "8", "9"),
            ("-", "+", "/"),
            ("x", "=", "a"),
            (".")
        )

        for r, row in enumerate(ls):
            for c, item in enumerate(row):
                bt = tk.Button(master, text=item, command=lambda char=item:self.on_press(char))
                bt.grid(row=r, column=c)

    def on_press(self, char):
        print(char)

# --- main ---

root = tk.Tk()
cal = Calc(root)
root.mainloop()
furas
  • 134,197
  • 12
  • 106
  • 148
  • Thank you furas that solved it for me as im sure your aware. I actually did try using lambda but just wasn't sure the best way to implement it. Thanks again ! – Nick Jan 02 '18 at 13:03