执行特定操作后如何刷新tkinter Frame和listBox?

时间:2018-10-05 21:51:24

标签: python tkinter

我在tkinter上有两个列表框,我想做的是双击一个列表框中的项目,将其添加到列表中,然后在另一个列表框中显示它。当前,添加到列表部分正在运行,但是由于某种原因它没有显示在另一个列表框中。

import tkinter as tk

testList = ["dog", "cat", "orange"]
newList = []

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self._frame = HomePage

class HomePage(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.config(width=300, bg='white', height=500, relief='sunken', borderwidth=2)

        self.reportNames = tk.StringVar(value=tuple(testList))
        self.lbox = tk.Listbox(self, listvariable=self.reportNames, height=15, width=50, borderwidth=2)
        self.lbox.pack()
        self.lbox.bind('<Double-1>', lambda x: addButton.invoke())

        addButton = tk.Button(self, text='Select', command=self.selection)
        addButton.pack()

        self.testNames = tk.StringVar(value=newList)
        self.lbox2 = tk.Listbox(self, listvariable=self.testNames, height=15, width=50, borderwidth=2)
        self.lbox2.pack()

    def selection(self):
        addThis = self.lbox.selection_get()
        print(self.lbox.selection_get())
        newList.append(addThis)
        print(newList)


if __name__ == "__main__":
    global app
    app = SampleApp()
    sidebar = HomePage(app)
    sidebar.pack(expand=False, fill='both', side='left', anchor='nw')
    app.geometry("1200x700")
    app.mainloop()

1 个答案:

答案 0 :(得分:2)

您的StringVar testNames不会跟踪对newList所做的更改,您需要在newList每次更改时更新StringVar。

def selection(self):
    addThis = self.lbox.selection_get()
    print(self.lbox.selection_get())
    newList.append(addThis)
    print(newList)
    # update StringVar
    self.testNames.set(newList)