Tkinter Lambda函数 [英] Tkinter lambda function
问题描述
(如家庭作业"标签所示,这是计算机科学中 big 项目的一部分.)
(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
有关所有代码,请参见我的小代码查看器(正在建设中) !)
For all of the code, see my little Code Viewer (under construction!)
问题似乎在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定义为采用一个具有默认值的参数,则默认值是在定义时确定的(并固定的).现在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函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!