簡體   English   中英

Python3:使用 exec() 創建函數

[英]Python3: use exec() to create a function

我正在使用 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=...部分將當前循環值綁定為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()函數會在此處返回一個新函數,用作按鈕命令。

免責聲明:我沒有測試過這個。

使用字典來存儲您的所有函數,例如:

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(),除非你完全知道它有什么安全問題,你知道該產品不會在另一台機器上使用,或者你真的別無選擇。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM