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

时间:2014-08-29 01:56:45

标签: python tkinter

新手在这里。我和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()

1 个答案:

答案 0 :(得分:1)

有一些很好的教程。我通常会在这里提到: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()