Tkinter: How to dynamically insert items to another listbox?

做~自己de王妃 提交于 2021-01-29 04:55:38

问题


Newbie here. I am struggling with Tkinter a bit. I have much more complex program but I created this little script to show you what I'm trying to achieve. I have two listboxes, first one contains some items. When I select one item from first listbox, I want certain thing to be inserted into second listbox. I know that this has to be done via some loop or sth because if you run this script, second listbox has item 4480104160onselect instead of index integer of item in first listbox.

I am having problems to look this up in documentation so if you point me to specific part of it or some tutorial, that will work as well. Thank you very much.

Here is the code:

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:


There are some good tutorials. I usually refer to ones here: http://effbot.org/tkinterbook/listbox.htm or here: http://www.tutorialspoint.com/python/tk_listbox.htm, I prefer the first link because its more verbose.

[EDIT: Just changing the return line to not return but inserting into listbox l2 works.] [EDIT 2: Passing arguments to 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()


来源:https://stackoverflow.com/questions/25560613/tkinter-how-to-dynamically-insert-items-to-another-listbox

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!