Search code examples
pythontkinterwidgetbindvisibility

Detect when a widget change from visible to invisible or the opposite


Is it possible to be informed when we a widget which was visible become invisible .pack_forget() or an invisible widget become visible .pack() ?

Something Like button.bind("<Visible>", func_triggered_when_the_button_become_visible)

I want to hide and show entire frames and when I hide the widgets inside, I want their values to be reset.


Solution

  • I think <Map> is what your looking for, as per acw1668 suggestions. Here is an example to make you understand better:

    from tkinter import *
    from tkinter import messagebox
    
    root = Tk()
    
    def check(event): #function to be triggered only when the button is visible
        messagebox.showinfo('Visible','Seeing this message only because button is visible')
    
    b = Button(root,text='Im going to disappear') #making button but not packing it(invisible)
    
    b1 = Button(root,text='Click me to make the button disappear',width=50,command=lambda: b.pack_forget()) #to hide the button(to make invisible)
    b1.pack(padx=10)
    
    b2 = Button(root,text='Click me to make the button appear',width=50,command=lambda: b.pack()) #to show the button(to make visible)
    b2.pack(padx=10)
    
    b.bind('<Map>',check) #every time button is visible, check() is triggered
    
    root.mainloop()
    

    Ive commented to understand this better, do let me know if any doubts.

    A bit more on <Map> from the docs:

    The Map and Unmap events are generated whenever the mapping state of a window changes.

    Windows are created in the unmapped state. Top-level windows become mapped when they transition to the normal state, and are unmapped in the withdrawn and iconic states. Other windows become mapped when they are placed under control of a geometry manager (for example pack or grid).

    A window is viewable only if it and all of its ancestors are mapped. Note that geometry managers typically do not map their children until they have been mapped themselves, and unmap all children when they become unmapped; hence in Tk Map and Unmap events indicate whether or not a window is viewable.