1
myButtons = [
    "E", "CE", "C", "/", "%",
    "7", "8", "9", "*", "x²",
    "4", "5", "6", "-", "√",
    "1", "2", "3", "+", "^",
    "0", ".", "+/-", "!", "="
]

for i in myButtons:
    for j in range(0,4):
        for k in range(0,4):
            tkinter.Button(window, text=i,bg="blue", width=10, height=3, command=echo(i)).grid(row=j, column=k)

Can't cycle array elements into buttons, i expected buttons with value from array, but got last element as value of many buttons. Why it is happening?

2 Answers 2

4

I think you wanted to do this

myButtons = [
    ["E", "CE", "C", "/", "%"],
    ["7", "8", "9", "*", "x²"],
    ["4", "5", "6", "-", "√"],
    ["1", "2", "3", "+", "^"],
    ["0", ".", "+/-", "!", "="]
]

for j, row in enumerate(myButtons):
    for k, i in enumerate(row):
            tkinter.Button(window, text=i,bg="blue", width=10, height=3, command=echo(i)).grid(row=j, column=k)

Note, I have changed myButtons to a list of lists as I am assuming this is a static list. If you want to use original list, we can refactor the solution by getting the quotient and remainder on division by 5 as j and k respectively

Sign up to request clarification or add additional context in comments.

Comments

1

I suggest such a code:

import tkinter as tk
from tkinter import messagebox


def echo(text):
    tk.messagebox.showinfo('info', text)

root = tk.Tk()
myButtons = [
    "E", "CE", "C", "/", "%",
    "7", "8", "9", "*", "x²",
    "4", "5", "6", "-", "√",
    "1", "2", "3", "+", "^",
    "0", ".", "+/-", "!", "="
]

for i, text in enumerate(myButtons):
    tk.Button(root, text=text, bg="blue",
              width=10, height=3,
              command=lambda t=text: echo(t)).grid(row=i//5, column=i % 5)
root.mainloop()

10 Comments

@Imperions your code doesn't work properly because you are going to create 16 buttons for every myButtons element. I. e. 16 buttons for "E", 16 for "CE" and so on.
@Imperions also echo(i) is a mistake probably. You should put a function there, without (). If you need to pass arguments in, then you can use a lambda this way: command=lambda i: echo(i)
it returns error: TypeError: <lambda>() missing 1 required positional argument: 'i'
@Imperions oh, sorry, my bad. I fixed it and updated my answer.
@Imperions a function passed to command parameter would take no arguments when the click event occurs. So we use a named argument (t=text) in order to 'transport' the text variable into the lambda. The lambda works as a delegate to echo function. It's a common trick to pass arguments to event handlers.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.