且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为列表中的每个项目制作 tkinter 按钮?

更新时间:2023-11-28 15:44:22

这里有两件事:

  1. 您需要将以下行缩进一级:

  1. You need to indent the following line one level:

button.pack()

目前,您只能在最后一个按钮上调用 pack 方法.进行此更改将导致为每个按钮调用它.

Currently, you only have the pack method being called on the last button. Making this change will cause it to be called for each button.

所有按钮都将 'item3' 发送到 func,因为这是 item 的当前值.重要的是要记住,由 lambda 函数包围的表达式是在运行时计算的,而不是在编译时计算的.

All of the buttons are sending 'item3' to func because that is the current value of item. It is important to remember that the expression enclosed by a lambda function is evaluated at run-time, not compile-time.

但是,同样重要的是要记住,函数的参数及其默认值(如果有)都是在编译时而不是运行时计算的.

However, it is also important to remember that both a function's parameters as well as their default values (if any) are evaluated at compile-time, not run-time.

这意味着您可以通过为 lambda 提供一个默认值设置为 item 的参数来解决问题.这样做将为 for 循环的每次迭代捕获"item 的值.

This means that you can fix the problem by giving the lambda a parameter whose default value is set to item. Doing so will "capture" the value of item for each iteration of the for-loop.

以下是解决这些问题的脚本版本:

Below is a version of your script that addresses these issues:

from Tkinter import *
root = Tk()
def func(name):
    print name
mylist = ['item1', 'item2', 'item3']
for item in mylist:
    button = Button(root, text=item, command=lambda x=item: func(x))
    button.pack()

root.mainloop()