Home > Enterprise >  How to access a widget in another widget event handler : Tkinter
How to access a widget in another widget event handler : Tkinter

Time:11-16

I am creating a GUI in tkinter having a listbox and a Text item in a child window which appears after a button click. Listbox is displaying values of a dict which are basically names of files/directories in disk image. I want to change the text of Text widget on <ListboxSelect> event and display type or path of selected file.

Now I cant make Text global since it has to appear on child window, so I need a way to access it in event handler of Listbox. Can I give handler reference of Textbox?

Here is my code;

def command(event):
    ...          #Need to change the Text here, how to access it?

def display_info(dict,filename):
    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind(<ListboxSelect>,command)

def upload_file():



window = Tk()
upl_button = Button(command=upload_file)

window.mainloop()
    

Is there a way to create a textview as global and then change its properties later to be displayed in child_window etc.

CodePudding user response:

Two solutions here that I can think of is to make textview a globalized variable or to pass textview to command() as an argument.

  • Parameter solution:
def command(event,txtbox):
    txtbox.delete(...)

def display_info(dict,filename):
    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind('<ListboxSelect>',lambda event: command(event,textview))
  • Or simply just globalize it:
def command(event):
    textview.delete(...)

def display_info(dict,filename):
    global textview

    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind('<ListboxSelect>',command)

While saying all this, it is good to keep in mind that creating more than one instance of Tk is almost never a good idea. Read: Why are multiple instances of Tk discouraged?

  • Related