Home Ask Login Register

Developers Planet

Your answer is one click away!

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.frame = Frame(master)

        self.questionList = Listbox(self.frame)

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

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

class AddToListbox:

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

        self.frame = Frame(master)

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

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

    def add_to_listBox(self):
        # HELP ME HERE

if __name__ == '__main__':
    root = Tk()


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


Leave an answer

Quote of the day: live life