Tkinter lambda 函数

编程入门 行业动态 更新时间:2024-10-27 20:31:21
本文介绍了Tkinter lambda 函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

(正如家庭作业"标签所示,这是一个大计算机科学项目的一部分.)

(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 函数

本文发布于:2023-11-28 09:21:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1641827.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   Tkinter   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!