Tkinter Create Buttons From List Each With Its Own Function
I want to create buttons from a list and assign each button a function based on the list item. I tried below and the button doesn't respond to a click. I see solutions where a lamb
Solution 1:
Your list contains strings; it needs to contain functions
lst = [North,South,East,West]
Solution 2:
Faster and better:
import tkinter as tk
def onbutton_click(label):
print('selected ', label)
lst = ['North','South','East','West']
win = tk.Tk()
win.title = 'Compass'
for col,Direction in enumerate(lst):
butName = tk.Button(win, text=Direction, command=lambda e=Direction: onbutton_click(e))
butName.grid(row=0, column=col)
win.mainloop()
or your way:
import tkinter as tk
def North():
print('slected North')
def South():
print('slected South')
def East():
print('slected East')
def West():
print('slected West')
lst = [North, South,East, West]
win = tk.Tk()
win.title = 'Compass'
for col,Direction in enumerate(lst):
butName = tk.Button(win, text=Direction.__name__, command=Direction)
butName.grid(row=0, column=col)
win.mainloop()
I also set the row as 0 cause there is no need to be 1.
Post a Comment for "Tkinter Create Buttons From List Each With Its Own Function"