简体   繁体   English

python tkinter listbox:添加项目

[英]python tkinter listbox: adding items

At program startup, I add some items to my listbox like this: 在程序启动时,我将一些项目添加到列表框中,如下所示:

for widget in WidgetNames:
    listbox.insert(0, widget)

WidgetNames is obviously a list of some items, eg "Button" and "Canvas". WidgetNames显然是一些项目的列表,例如“ Button”和“ Canvas”。 The thing is, the listbox doesn't show the items that are added with above code. 问题是,列表框不显示使用上述代码添加的项目。 However, 然而,

for widget in WidgetNames:
    listbox.insert(0, widget)
    print(listbox.get(0))

prints "Button" and "Canvas", and 打印“按钮”和“画布”,以及

for widget in WidgetNames:
    listbox.insert(0, widget)
print(listbox.size())

prints 2, which obviously is the correct number of items it contains. 打印2,这显然是其中包含的正确项目数。 All the listbox shows after items are added is an empty line. 添加项目后显示的所有列表框为空行。 I've tried listbox.see(0) and listbox.index(0), but that didn't help. 我已经尝试过listbox.see(0)和listbox.index(0),但这没有帮助。 Any ideas why the items aren't added properly? 有什么想法为什么不能正确添加项目?

The code you're showing is not the problem -- it must be some other code which you are not showing. 您所显示的代码不是问题,它必须是您显示的其他代码。 Please try to reproduce your problem in as small a compass as possible and edit your answer to include that minimal code. 请尝试使用尽可能小的指南针重现您的问题,然后编辑您的答案以包含最少的代码。 Here's a small script to show that the code you show is actually OK: 这是一个小脚本,用于说明您显示的代码实际上是可以的:

from Tkinter import *

master = Tk()
listbox = Listbox(master)
listbox.pack()

WidgetNames = ['Button', 'Canvas']
for widget in WidgetNames:
    listbox.insert(0, widget)

mainloop()

This code runs fine on my box (Ubuntu 10.4, Python 2.6) and, exactly as expected, shows the two items ('Canvas' first). 这段代码可以在我的机器上正常运行(Ubuntu 10.4,Python 2.6),并且完全按预期显示了这两个项目(第一个是“画布”)。 If this does not behave that way on your box, please edit your answer to provide the minutest details about said box;-). 如果这个行为你的盒子那样,请编辑您的答案提供有关上述箱;-)的微小细节的。

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

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