How would I make a method which is run every time a frame is shown in tkinter

Tkinter has low level events such as <Visibility> and <Map> which should fire when the pages change. Unfortunately, these don’t work reliably on all platforms.

The simplest and most robust solution is to generate your own event. You can create and bind to a custom event by specifying the event inside << and >> (eg: <<ShowFrame>>).

First, change show_frame to send an event to a window when it is shown:

def show_frame(self, page_name):
    ...
    frame.event_generate("<<ShowFrame>>")

Next, each page can bind to this event if it needs to be notified when it is made visible:

class UploadPage(tk.Frame):
    def __init__(self, parent, controller):
        ...
        self.bind("<<ShowFrame>>", self.on_show_frame)

    def on_show_frame(self, event):
        print("I am being shown...")

Leave a Comment