使按钮更改列表框的内容

时间:2015-04-21 11:37:08

标签: python tkinter listbox

我正试图通过按下按钮将列表框的选定元素移动到另一个列表框。但是,我不明白如何让按钮知道它正在获取哪些列表框并将数据发送到。

这是我的代码:

import tkinter as tk
from tkinter import ttk

class MoveItems(ttk.Button):
#the button should move things from the origin listbox to the destiny
#listbox
    def __init__(self, parent, origin, destiny, label):
        ttk.Button.__init__(self, parent, text = label)
        self.parent = parent
        self.origin = origin #is this correct?
        self.destiny = destiny
        self.command = self.moveToDestiny

    def moveToDestiny(self):
        selected_items = self.origin.curselection()
        selected = [self.origin.get(i) for i in selected_items]
        self.destiny.list_update(selected)


class ListOfThings(tk.Listbox):
#here are my listboxes
#list_update adds a list to the listbox
        def __init__(self, parent, list_to_show):
            tk.Listbox.__init__(self, parent, selectmode = tk.EXTENDED)
            self.list_to_show = list_to_show
            self.parent = parent
            self.list_update(list_to_show)

        def list_update(self, list):
            for item in list:
                self.insert(tk.END, item)


class SelectFromList(ttk.Frame):
    def __init__(self, parent, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.parent = parent
        list1 = ["A", "B", "C"]
        list2 = ["D", "E", "F"]

        self.leftList = ListOfThings(self, list1)
        self.rightList = ListOfThings(self, list2)
        self.moveRight = MoveItems(self, self.leftList, self.rightList, "-->")

        self.leftList.pack(side = "left")
        self.moveRight.pack(side = "left")
        self.rightList.pack(side = "right")

if __name__ == "__main__":
    root = tk.Tk()
    SelectFromList(root).pack(side="top", fill="both", expand=True)
    root.mainloop()

我不确定我的MoveItems按钮的__init__是否真正跟踪起源和命运列表框。我试图打印selected项目,但终端上没有任何内容。

1 个答案:

答案 0 :(得分:2)

我认为self.command = self.moveToDestiny不会做你想做的事。我们知道command是Button的init方法中参数的名称,但这并不一定意味着该值随后会存储在command属性中。

在致电command时尝试指定Button.__init__

class MoveItems(ttk.Button):
#the button should move things from the origin listbox to the destiny
#listbox
    def __init__(self, parent, origin, destiny, label):
        ttk.Button.__init__(self, parent, text = label, command=self.moveToDestiny)

现在,您的按钮应该成功地将项目添加到右侧的列表框中。


我敢打赌你也希望从左框中删除所选项目。您必须制作另一个从列表中移除项目的ListOfThings方法。类似的东西:

    def list_remove(self, items_to_remove):
        items = self.get(0, tk.END)
        remaining_items = [item for item in items if item not in items_to_remove]
        self.delete(0, tk.END)
        self.list_update(remaining_items)

(可能不是最好的方法,但这只是一个例子)

然后你可以在moveToDestiny中调用它。

def moveToDestiny(self):
    selected_items = self.origin.curselection()
    selected = [self.origin.get(i) for i in selected_items]
    self.destiny.list_update(selected)
    self.origin.list_remove(selected)