在循环中的 lambda 函数定义期间设置附加参数 - 调用函数时结果相同

Setting additional arguments during lambda function definition in a loop - same result when function is called

我想在循环中创建图形回调,每个图形的回调具有不同的附加输入参数。在下面的代码片段中,无论我点击哪个数字,函数都会打印“B”。

import matplotlib.pyplot as plt
import numpy as np

def onclick(event, key):
    print(key)

for k in ["A", "B"]:
    x = np.arange(1,10)
    y = x**2
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title(k)
    ax.plot(x,y)
    cid = fig.canvas.mpl_connect('button_press_event', lambda tmp: onclick(tmp, k))

替换

lambda tmp: onclick(tmp, k)

functools.partial(onclick, key=k)

完整示例:

from functools import partial
import numpy as np
import matplotlib.pyplot as plt

def onclick(event, key):
    print(key)

for k in ["A", "B"]:
    x = np.arange(1,10)
    y = x**2
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_title(k)
    ax.plot(x,y)
    cid = fig.canvas.mpl_connect('button_press_event', partial(onclick, key=k))

plt.show()