我正在使用 tkinter 创建一个应用程序,目前我制作了很多按钮,所以我需要用不同的命令绑定所有按钮,我想用它exec()
来创建功能。
strategy=None
exec("global commandbutton"+str(len(strategicpoint)+1)+"\ndef commandbutton"+str(len(strategicpoint)+1)+"():\n\tglobal strategy\n\tstrategy="+str(len(strategicpoint)))
commandline=eval('commandbutton'+str(len(strategicpoint)+1))
imgx=tk.Button(win,image=towert,command=commandline)
对于更清洁的解决方案:
global commandbutton{...}
def commandbutton{...}():
global strategy
strategy={...}
我希望我的代码像上面一样运行并且它运行,但后来我调用命令和测试print(strategy)
,(我点击了按钮/调用了命令)它None
在我想要它打印其他东西时打印。
绝对没有必要使用exec()
或eval()
这里。
exec
使用 、使用闭包,或者仅通过将参数绑定到 lambda 函数或functools.partial()
.因此,如果您有一个具有递增strategicpoint
值的循环,我会这样做:
def set_strategy(point):
global strategy
strategy = point
buttons = []
for strategicpoint in range(1, number_of_points + 1):
imgx = tk.Button(win, image=towert, command=lambda point=strategicpoint: set_strategy(point))
buttons.append(imgx)
该lambda point=...
部分将当前循环值绑定为创建point
的新函数对象的参数的默认值lambda
。当不带参数调用该函数时(就像单击按钮时所做的那样),新函数使用当时分配的整数值strategicpoint
来调用set_strategy(point)
.
您还可以使用内部函数使用的闭包,即外部函数中的局部变量。每次调用外部函数时都会在外部函数内创建嵌套的内部函数,因此它们与由同一外部函数创建的其他函数对象分开:
def create_strategy_command(strategypoint):
def set_strategy():
global strategy
strategy = strategypoint
return set_strategy
然后在创建按钮时,使用:
imgx = tk.Button(win, image=towert, command=create_strategy_command(strategicpoint))
请注意,调用该create_strategy_command()
函数会在此处返回一个新函数,用作按钮命令。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句