简体   繁体   English

在 Python Tkinter 中将项目添加到列表框

[英]Adding items to Listbox in Python Tkinter

I would like my Listbox widget to be updated upon clicking of a button.我希望在单击按钮时更新我的​​列表框小部件。 However I encountered a logic error.但是我遇到了一个逻辑错误。 When I click on the button, nothing happens.当我点击按钮时,没有任何反应。 No errors at all.完全没有错误。

listOfCompanies: [[1, ''], [2, '-'], [3, '@ASK TRAINING PTE. LTD.'], [4, 'AAIS'], [5, 'Ademco'], [6, 'Anacle']

def populatebox():
            listBox.insert("end", listOfCompanies)

btn = Button(self, text="Update list", command = lambda: populatebox())
btn.pack()

If you're looking to just insert every tuple into the Listbox from the list as they are without separating out the tuple then there are two major changes.如果你正在寻找只需插入每一个tupleListboxlist ,因为它们没有分离出的tuple则有两个重大变化。

First you cannot declare a list as list: [1, 2, 3, ...] , it must be list = [1, 2, 3, ...] .首先,您不能将列表声明为list: [1, 2, 3, ...] ,它必须是list = [1, 2, 3, ...]

Secondly, you are currently attempting to insert the entire list onto one entry in the Listbox .其次,您当前正尝试将整个list插入到Listbox一个条目中。 You should instead iterate over them, see below for an example:您应该迭代它们,请参见下面的示例:

from tkinter import *

root = Tk()

listBox = Listbox(root)
listBox.pack()

listOfCompanies = [[1, ''], [2, '-'], [3, '@ASK TRAINING PTE. LTD.'], [4, 'AAIS'], [5, 'Ademco'], [6, 'Anacle']]

def populatebox():
    for i in listOfCompanies:
        listBox.insert("end", i)

btn = Button(root, text="Update list", command = lambda: populatebox())
btn.pack()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM