Say I have a list of strings: obj = ['One','Two','Three'] , how could I turn each value into this list into a function where they all perform very similar functions? For example:
def one(): print("one") def two(): print("two") def three(): print("three")
Now I know that you can predefine functions and use a dictionary (as shown below), but I will say that I wanted many functions to be created, this would require a lot of code, and therefore I would like to know if there is a shorter way , I can do it.
import tkinter as tk def one(): print("one") def two(): print("two") def three(): print("three") obj = ['One','Two','Three'] func = {'One': one, 'Two': two, 'Three': three} def create_btn(): btns = {} for i in obj: text = i for col in range(1): for row in range(len(obj)): btns[row, col] = tk.Button(canvas, text=str(text), command=func[i]).grid(column=col, row=row) btns[row, col] = canvas.create_window(50, row, window = btns[row, col]) canvas.pack() root = tk.Tk() root.geometry = ("750x600") btn_frame = tk.Frame(root) canvas = tk.Canvas(root) create_btn() root.mainloop()
function python list
Ernxst
source share