Yot Yot5 February 2016

How do you update a TkInter ListBox from child window?

I've recently started working on my first TkInter program. I've been able to find answers to most of my questions, but there's one problem I haven't been able to resolve.

At one point in my code, I want the user to be able to input a name in a child window. After clicking a button in this window, an item with the inputted name will be added to a Listbox in the parent window.

My code (with all the unrelated widgets removed) is shown below. If you have an answer, bear in mind that I am a newcomer to TkInter (and programming in general), so please explain it in as much depth as possible.

Thanks in advance!

from tkinter import *

class HomePage:

    def __init__(self, master):

        self.master = master
        self.master.title("HomePage")

        self.frame = Frame(master)
        self.frame.pack()

        self.questionList = Listbox(self.frame)
        self.questionList.pack()

        self.button = Button(self.frame, text="Open AddToListbox window", command=self.open_AddToListbox)
        self.button.pack()

    def open_AddToListbox(self):
        self.topWindow = Toplevel(self.master)
        AddToListbox(self.topWindow)


class AddToListbox:

    def __init__(self, master):
        self.master = master
        self.master.title("AddToListbox")
        self.master.grab_set()

        self.frame = Frame(master)
        self.frame.pack()

        self.userInput = StringVar()
        self.entryBox = Entry(self.frame, textvariable=self.userInput)
        self.entryBox.pack()

        self.button = Button(self.frame, text="Add to listBox", command=self.add_to_listBox)
        self.button.pack()

    def add_to_listBox(self):
        # HELP ME HERE
        pass


if __name__ == '__main__':
    root = Tk()
    HomePage(root)
    root.mainloop()

Answers


Bryan Oakley February 2016

The simplest solution is to give AddToListbox a reference to the listbox so that it can directly add the value.

First, make sure AddToListbox can accept and save the reference:

class AddToListbox:

    def __init__(..., target):
        ...
        self.target = target
        ...

Next, use the reference in add_to_listBox:

def add_to_listBox(self):
    new_value = self.entryBox.get()
    self.target.insert("end", new_value)

Finally, pass the listbox into the constructor when creating the instance of AddToListbox:

def open_AddToListbox(...):
    ...
    AddToListbox(..., self.questionList)

Note: This is not the only solution. For example, instead of passing in a reference to the listbox, you could pass in self, or a reference to some other function that does the insert.

The point is, if class B needs to access something in class A, class B must be given a reference to A or some attribute of A.

Post Status

Asked in February 2016
Viewed 1,733 times
Voted 12
Answered 1 times

Search




Leave an answer