Use tkinter loop to make similar widgets with different outputs
Question:
I’m trying to make a loop for adding widgets.
The code is supposed to add 5 buttons, each button giving a different number when pressed.
import tkinter as tk
top = tk.Tk()
m1 =tk.Frame(width=400, height=400)
m1.pack()
def thingie(s):
print(s)
for i in range(5):
btn = tk.Button(m1, text='Button'+str(i), command=lambda:thingie(i))
btn.place(x=0, y=i*35)
top.mainloop()
The code runs with no errors, but each button gives me the same number instead of different numbers. How do I fix this?
Answers:
import tkinter as tk
top = tk.Tk()
m1 =tk.Frame(width=400, height=400)
m1.pack()
def thingie(s):
print(s)
for i in range(5):
btn = tk.Button(m1, text='Button'+str(i), command=lambda m=i: thingie(m))
btn.place(x=0, y=i*35)
top.mainloop()
I’m trying to make a loop for adding widgets.
The code is supposed to add 5 buttons, each button giving a different number when pressed.
import tkinter as tk
top = tk.Tk()
m1 =tk.Frame(width=400, height=400)
m1.pack()
def thingie(s):
print(s)
for i in range(5):
btn = tk.Button(m1, text='Button'+str(i), command=lambda:thingie(i))
btn.place(x=0, y=i*35)
top.mainloop()
The code runs with no errors, but each button gives me the same number instead of different numbers. How do I fix this?
import tkinter as tk
top = tk.Tk()
m1 =tk.Frame(width=400, height=400)
m1.pack()
def thingie(s):
print(s)
for i in range(5):
btn = tk.Button(m1, text='Button'+str(i), command=lambda m=i: thingie(m))
btn.place(x=0, y=i*35)
top.mainloop()