繁体   English   中英

Tkinter:如何将项目动态插入另一个列表框?

[英]Tkinter: How to dynamically insert items to another listbox?

新手在这里。 我在Tkinter上有点挣扎。 我的程序要复杂得多,但是我创建了这个小脚本来向您展示我要实现的目标。 我有两个列表框,第一个包含一些项目。 当我从第一个列表框中选择一个项目时,我希望将某些东西插入第二个列表框中。 我知道这必须通过某种循环来完成,因为如果您运行此脚本,则第二个列表框将具有项4480104160onselect而不是第一个列表框中的项的索引整数。

我在文档中查找时遇到了问题,因此,如果您将其指向本文档的特定部分或一些教程,也可以使用。 非常感谢你。

这是代码:

from Tkinter import *

root = Tk()

parentlist = ['one','two','three']
l1 = Listbox()
for item in parentlist:
    l1.insert(END, item)

l1.grid(row=0, column=0)

def onselect(event):
    w = event.widget
    index = w.curselection()[0]
    print "You selected: %d" % int(index)
    return int(index)

l1select = l1.bind('<<ListboxSelect>>',onselect)

l2 = Listbox()
l2.insert(END, l1select )

l2.grid(row=0, column=1)
root.mainloop()

有一些很好的教程。 我通常在这里指的是: http : //effbot.org/tkinterbook/listbox.htm或这里: http : //www.tutorialspoint.com/python/tk_listbox.htm ,我喜欢第一个链接,因为它比较冗长。

[编辑:仅将返回行更改为不返回,而是将其插入列表框l2即可。] [编辑2:将参数传递给onselect]

from Tkinter import *

root = Tk()

parentlist = ['one','two','three']
l1 = Listbox()
for item in parentlist:
    l1.insert(END, item)

l1.grid(row=0, column=0)
l2 = Listbox()

l2.grid(row=0, column=1)

def onselect(event, test):
    w = event.widget
    index = w.curselection()[0]
    print "You selected: {0} and test variable is {1}".format(index, test) 
    l2.insert(END, index ) # Instead of returning it, why not just insert it here?

l1select = l1.bind('<<ListboxSelect>>',lambda event: onselect(event, 'Test'))

root.mainloop()

暂无
暂无

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

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