Python3:使用exec()创建函数

2024-04-29 04:35:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用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。你知道吗


Tags: 函数命令none应用程序lentkinter按钮global
2条回答

这里绝对不需要使用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=...部分将当前循环值绑定为lambda创建的新函数对象的point参数的默认值。如果在没有参数的情况下调用该函数(就像单击按钮时所做的那样),那么新函数将使用当时分配给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()函数在这里返回一个新函数,用作button命令。你知道吗

免责声明:我还没有测试过这个。你知道吗

使用字典存储所有函数,例如:

option = "default"
def change_option(target):
    global option
    option = target

def f1():
    print("foo")
def f2():
    print("bar")

my_functions = {
    "select1": f1,
    "select2": f2
    "default": None
    }

imgx=tk.Button(win,image=towert,command=my_functions[option])  # None
swapper = tk.Button(win, image=towert, lambda: change_option("select2")) # button to change the command if you want it
imgx=tk.Button(win,image=towert,command=my_functions[option]) # print("bar")
change_option("select1")
imgx=tk.Button(win,image=towert,command=my_functions[option]) # print("foo")

你可能不用字典也能过得去,但我认为这是相当干净的。永远不要使用exec()或eval(),除非您完全知道它有什么安全隐患,您知道该产品不会在其他机器上使用,或者您真的没有其他选择。你知道吗

相关问题 更多 >