How to Set a Non-First Tab as Selected in PySimpleGUI Window Startup

What will you learn?

In this tutorial, you will learn how to set a specific tab as selected when opening a PySimpleGUI window, even if it’s not the first tab.

Introduction to the Problem and Solution

When working with PySimpleGUI, the default behavior is to have the first tab selected when a window with tabs is opened. However, there are instances where you may want a different tab to be initially selected. To address this requirement, you can utilize the selected parameter while defining individual tabs within the window.

By leveraging the selected parameter in PySimpleGUI for a particular tab, you gain the ability to control which tab is active upon window startup. This empowers you to tailor the user interface and experience based on your specific needs and preferences.

Code

import PySimpleGUI as sg

# Create layout with multiple tabs
layout = [
    [sg.TabGroup([[sg.Tab('Tab 1', layout=[[sg.Text('Content of Tab 1')]], key='-TAB1-', selected=True),
                   sg.Tab('Tab 2', layout=[[sg.Text('Content of Tab 2')]], key='-TAB2-', selected=False)]])],
    [sg.Button('Submit')]
]

window = sg.Window('Window with Tabs', layout)

while True:
    event, values = window.read()
    if event == sg.WIN_CLOSED:
        break

window.close()

# Copyright PHD

Explanation

  • Developed a PySimpleGUI window containing two tabs using sg.Tab.
  • Assigned unique keys to each sg.Tab.
  • By setting selected=True for one tab (e.g., -TAB1-), we ensure its activation during startup.
  • The other tab (-TAB2-) is initialized with selected=False, rendering it inactive initially.
    How can I add more tabs to this code?

    To incorporate additional tabs, insert extra sg.Tab elements within the [[ ]].

    Can I change which tab is selected based on some condition?

    Yes, dynamically set or alter the selected tab based on conditions within your code.

    Is it possible to style or customize the appearance of tabs?

    Customize tab appearances using themes and element configuration parameters provided by PySimpleGUI.

    What happens if no tab is set as selected?

    If no specific selection is made during initialization, typically, the first tab will be automatically chosen by default.

    Can I disable user interaction for certain tabs?

    Adjust properties accordingly to disable interaction or make specific tabs read-only.

    Conclusion

    In conclusion we have learned how to set a non-first tab as the initial selection in a PySImpleGui windoW.

    Leave a Comment