-2

I am trying to learn how to use tkinter and encountered a problem with buttons. What I think is happening is when I start the program it automatically calls the functions of the buttons whenever they are initialized.

code in question:

import tkinter as tk
test = tk.Tk()

x = lambda a: int((a - (a) % 3) / 3)

for i in range(9):
frame = tk.Frame(
    master=test,
    padx=1,
    pady=1,
    borderwidth=1
)

frame.grid(row=x(i), column=(i % 3))
    button = tk.Button(
        text=i,
        master=frame,
        width=10,
        height=5,
        bg="#333333",
        fg="#ffffff",
        command=print(i)
    )
    button.pack()

test.mainloop()
  • 3
    Does this answer your question? [How to pass arguments to a Button command in Tkinter?](https://stackoverflow.com/questions/6920302/how-to-pass-arguments-to-a-button-command-in-tkinter) – Saad Jun 20 '20 at 07:10
  • 1
    I think you should add lambda to your command for the button if you want to pass arguments. So that you’d get: command = lambda : print(i) – Jem Jun 20 '20 at 07:26

1 Answers1

-1

All functions with () will be executed immediately. Try to wrap your function print(i) into lambda function like that command=lambda _: print(i) and call it with command()

Artyom Vancyan
  • 5,029
  • 3
  • 12
  • 34
BogdanKostyuk
  • 91
  • 2
  • 4