Tkinter Tab Activation

One thing we can do with our form is to get which tab is the currently active one. We'll want to reload the records from the database only if a new one has been added. For that to happen, we'll need to know which tab has been clicked on.

The first thing to do is something called binding. You do the binding on the parent tab and specify a function that you want to implement.

Locate these two lines in your code:

tab_parent.add(tab1, text="All Records")
tab_parent.add(tab2, text="Add New Record")

Just before these two lines, add the following:

tab_parent.bind("<<NotebookTabChanged>>", on_tab_selected)

In the round brackets of bind, we have this:

<<NotebookTabChanged>>", on_tab_selected

Between double quotes and double pointy brackets, we have NotebookTabChanged. This is something called an event. After a comma, we have a function that's going to deal with this event: on_tab_selected. (on_tab_selected is just a function name, and we could have called it something else.)

PyCharm will probably have created a red underline for on_tab_selected. That's because we haven't created this function yet.

Scroll up to the top if your code. Give yourself some rom after the import statements. Now add the following function:

def on_tab_selected(event):

Notice the word event in the round brackets of on_tab_selected. The event will be NotebookTabChanged. Now add these two lines for the function:

selected_tab = event.widget.select()
tab_text = event.widget.tab(selected_tab, "text")

The first line sets up a widget selection object for the event. The second line specifies that it should be the text of the tab that we're interested in. We can test our two tabs in an if statement. Add this:

if tab_text == "All Records":

print("All Records tab selected")

if tab_text == "Add New Record":

print("Add New Record tab selected")

We're testing if the tab text is "All Records". If it is, we're just printing something out for now. The final if statement checks the tab text for "Add New Record". In other words, which ever tab it is a user clicks on, we catch it in an if statement and print something out. Later, we'll replace the print statements with something more useful.

Your code should look like this:

Python code to select a Tkinter tab

Run your program and watch what gets printed to the output window. When the form first loads, the All Records tab is selected, so "All Records tab selected" gets printed, even though you didn't select anything. Click on the two tabs and see what happens in the output window.

Before going any further, have a look at PyCharm and the edges of the code. You should notice a minus symbol:

PyCharm Python code expanded

You can click this to collapse the code in your functions. That way, it's easier to navigate your code when it gets too long:

PyCharm Python code collapsed

In the next lesson, we'll deal with images in labels. We'll need this for the photos in our project.

Tkinter Image Labels >