假设我有一个字符串列表:obj = ['One','Two','Three'],我怎样才能将此列表中的每个值转换为一个函数,它们都执行非常相似的函数?例如:
def one():
print("one")
def two():
print("two")
def three():
print("three")
Run Code Online (Sandbox Code Playgroud)
现在我知道你可以预先定义函数并使用字典(如下所示),但是说我想要创建很多函数,这需要很多代码才能这样做,因此我想知道是否有我可以用更短的方式来解决这个问题.
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 …Run Code Online (Sandbox Code Playgroud)