Python3:使用 exec() 创建函数

诺比

我正在使用 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()这里。

  • 函数不必按顺序命名。您也可以将函数对象存储在循环变量中,并使用该循环变量来创建 tkinter 钩子。
  • 您可以创建带有绑定参数的函数,而不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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章