-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?

3
  • this code is all in the class Calc by the way Commented Dec 30, 2017 at 10:51
  • 1
    I think your problem is similar as this one Commented Dec 30, 2017 at 11:00
  • See stackoverflow.com/q/17677649/7032856. Commented Dec 30, 2017 at 13:44

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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 !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.