(正如家庭作业"标签所示,这是一个大计算机科学项目的一部分.)
(As the 'homework' tag indicates, this is part of a big project in Computer Science.)
我正在使用 tkinter 在 Python 中编写 Jeopardy! 模拟,并且在按钮中使用 lambda 函数时遇到了一个大问题.假设 root = Tk() 和 categories 是一个列表.
I am writing a Jeopardy! simulation in Python with tkinter, and I'm having a big problem regarding the use of the lambda function in buttons. Assume root = Tk() and categories is a list.
# Variable to keep the buttons root._buttons = {} # Display headers on top of page for i in range(5): # Get category name for display in main window name = categories[i] b = Label(root, text=fill(name.upper(), 10), width=18, height=3, bg="darkblue", fg="white", font=("Helvetica bold", "", 11)) b.grid(row=0, column=i) # Create list of buttons in that variable (root._buttons) btnlist = [None]*5 # Display individual questions for j in range(5): # Make a button for the question b = Button(root, text="$" + str(200 * (j+1)), width=8, height=1, bg="darkblue", fg="orange", font=("Impact", "", 30)) b.cat = name b.value = 200 * (j + 1) b.sel = lambda: select(b.cat, b.value) # Add callback event to button print(b.cat, b.value, b.sel) b.config(command=b.sel) # Add button to window b.grid(row=j+1, column=i) # Append to list btnlist[j] = b root._buttons[categories[i]] = btnlist对于所有代码,请参阅我的小代码查看器(正在建设中)!)
它在 lambda: select(b.cat, b.value) 问题似乎发生的地方,因为当我单击板上的任何按钮时,它总是转到最后一个按钮董事会.我尝试过其他方法,不幸的是都使用 lambda,而且我还没有看到任何不涉及 lambda 的方法.
It's at lambda: select(b.cat, b.value) where the problem seems to occur, because when I click any button on the board, it always goes to the one last button on the board. I've tried other approaches, unfortunately all using lambda, and I have not seen any approach that does not involve lambda.
推荐答案更改
lambda: select(b.cat, b.value)到
lambda b = b: select(b.cat, b.value)在你的原始代码中,b 不是 lambda 的局部变量;它位于封闭范围内.一旦 for-loop 完成,b 会保留它的最后一个值.这就是 lambda 函数都使用最后一个按钮的原因.
In your original code, b is not a local variable of the lambda; it is found in enclosing scope. Once the for-loop is completed, b retains it last value. That is why the lambda functions all use the last button.
如果您将 lambda 定义为采用一个带有默认值的参数,则默认值在 lambda 被定义时确定(并固定).现在 b 是 lambda 的局部变量,当 lambda 被不带参数调用时,Python 将 b 设置为默认值,这很高兴根据需要设置为各种不同的按钮.
If you define the lambda to take one argument with a default value, the default value is determined (and fixed) at the time the lambda is defined. Now b is a local variable of the lambda, and when the lambda is called with no arguments, Python sets b to the default value which happily is set to various different buttons as desired.
更多推荐
Tkinter lambda 函数
发布评论