Lionel Yu
Lionel Yu

Reputation: 388

How to refresh the tkinter Frame and listBox after performing a specific action?

I have two listboxes on tkinter, what I'd like to do is double-click the item in one listbox, add it to the list, and have it show up in the other listbox. Currently, the adding to list part is working, but it's not showing up in the other listbox for some reason.

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()

Upvotes: 0

Views: 474

Answers (1)

strava
strava

Reputation: 765

Your StringVar testNames won't track changes made to newList, you need to update the StringVar every time newList changes.

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

Upvotes: 3

Related Questions