In the process of creating the application, rather cumbersome parts of the code appeared. I created an example of such sections of code
The main problem is that only "... .config..." should be placed in the loop.
from tkinter import *
import tkinter as tk
root = Tk()
root.geometry("500x300")
root.configure(bg="#FFFFFF")
root.title("TESTING")
button_1=Button(root,text="Click")
button_2=Button(root,text="Click")
button_3=Button(root,text="Click")
button_4=Button(root,text="Click")
#-----------------------------------------------------------
button_1.config(command=lambda: print('Button_1 presed'))
button_2.config(command=lambda: print('Button_2 presed'))
button_3.config(command=lambda: print('Button_3 presed'))
button_4.config(command=lambda: print('Button_4 presed'))
#-----------------------------------------------------------
button_1.pack()
button_2.pack()
button_3.pack()
button_4.pack()
root.mainloop()
#I tested this example, but it didn't work
for i in range(1,4):
f"button_{i}.config(command=lambda: print('Button_{i} presed'))"
CodePudding user response:
Edit: The typo was spotting by @TheLizzard. Is should be lambda j=j: my_fun(j)
Try this:
Code:
import tkinter as tk
root = tk.Tk()
root.geometry("200x200")
root.title("How to put in loop button.config")
def my_fun(k):
print(f'Btn No is : {str(k)}')
n=5 # number of buttons
for j in range(1,n):
e = tk.Button(root, text=j,command=lambda j=j: my_fun(j))
e.pack(padx=5, pady=j)
root.mainloop()
Screenshot: