假设我有一个字符串列表:obj = ['One','Two','Three']
,我怎样才能将此列表中的每个值转换为一个函数,它们都执行非常相似的函数?例如:
def one():
print("one")
def two():
print("two")
def three():
print("three")
现在我知道你可以预先定义函数并使用字典(如下所示),但是说我想要创建很多函数,这需要很多代码才能这样做,因此我想找出来如果有一个更短的方式,我可以解决这个问题。
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()
答案 0 :(得分:8)
使用闭包:
>>> def print_me(string):
... def inner():
... print(string)
... return inner
...
>>> functions = [print_me(s) for s in obj]
>>> functions[0]()
One
>>> functions[1]()
Two
>>> functions[2]()
Three
也许dict
会更方便:
>>> functions = {s:print_me(s) for s in obj}
>>> functions['One']
<function print_me.<locals>.wrapper at 0x102078bf8>
>>> functions['One']()
One
>>>
答案 1 :(得分:2)
如果你想管理这些名字,也可以使用exec:
这个简单的解决方案L=['one','two','three']
prog='def xxx():print("xxx")'
for name in L:
exec(prog.replace('xxx',name))
定义了三个函数。
>>>two()
two
>>>