Issue
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?
Solution
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()
Answered By - tafer
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.