-1

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.

aneela
  • 1,457
  • 3
  • 24
  • 45
  • 1
    Several instances of `tk.Tk()` is a bad idea - use `tk.Toplevel` instead. Also post an [mvce](https://stackoverflow.com/help/minimal-reproducible-example) – Reblochon Masque Nov 16 '21 at 06:07
  • You can make the Text instance global. There's nothing about the child window that would prevent that. – Novel Nov 16 '21 at 06:10
  • @Novel Can I create textview as global without declaring it child of child_w as child_w is dependent on upl_Button? I mean I have to add parent in its constructor? – aneela Nov 16 '21 at 06:18
  • @ReblochonMasque I have uploaded the mvce already. Its just two windows. Thanks for the suggestion of using Toplevel. – aneela Nov 16 '21 at 06:20
  • You can just make it global or pass it as a argument to the callback event – Delrius Euphoria Nov 16 '21 at 06:21
  • @aneela Your code is minimal, but not complete. I can't run that to test it. Show us a [mcve]. – Novel Nov 16 '21 at 06:21

1 Answers1

0

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?

Delrius Euphoria
  • 14,910
  • 3
  • 15
  • 46