PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 10, 2022

[FIXED] How to access a widget in another widget event handler : Tkinter

 July 10, 2022     global-variables, python, reference, tkinter     No comments   

Issue

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.


Solution

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?



Answered By - Delrius Euphoria
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing