为列表中的每个项目制作 tkinter 按钮? [英] Make tkinter buttons for every item in a list?

查看:34
本文介绍了为列表中的每个项目制作 tkinter 按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作一些按钮,带有我从数据库中返回的项目列表,所有这些按钮都调用传入列表项目的函数.类似于此代码的东西,但有效.此代码的问题在于所有按钮都使用 'item3' 调用该函数.

I would like to make some buttons, with a list of items I get back from a database, that all call a function passing in the list item. Something like this code but that works. The problem with this code is that all of the buttons call the function with 'item3'.

#!/usr/bin/env python
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:func(item))
button.pack()

root.mainloop()

推荐答案

这里有两件事:

  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()

这篇关于为列表中的每个项目制作 tkinter 按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆