Python tabs using tkinter
Python TTK Tabs Tutorial
In this tutorial, we’ll learn how to create tabs in Python using the ttk.Notebook
widget from the tkinter
library. Tabs are a great way to organize content in your GUI applications.
Code Example
# Import tkinter and ttk
import tkinter as tk
from tkinter import ttk
# Create the main window
root = tk.Tk()
root.title("Bonedev Python TTK Tabs Example")
# Create a Notebook widget (Tab container)
notebook = ttk.Notebook(root)
# Create two frames that will hold content for each tab
frame1 = ttk.Frame(notebook)
frame2 = ttk.Frame(notebook)
# Add frames as tabs to the notebook
notebook.add(frame1, text="Tab 1")
notebook.add(frame2, text="Tab 2")
# Add content to Tab 1
label1 = ttk.Label(frame1, text="This is the content of Tab 1.")
label1.pack(padx=20, pady=20)
# Add content to Tab 2
label2 = ttk.Label(frame2, text="This is the content of Tab 2.")
label2.pack(padx=20, pady=20)
# Pack the notebook widget into the main window
notebook.pack(padx=10, pady=10)
# Start the Tkinter main loop
root.mainloop()
How It Works
ttk.Notebook()
creates a tab container.ttk.Frame()
represents the content inside each tab.- The
notebook.add()
method adds frames to the tab container with a label. - Finally, the
root.mainloop()
starts the application loop.
Run the Code
Copy the code above into a Python file and run it. You’ll see a window with two tabs: Tab 1 and Tab 2. Each tab contains its own content.
Conclusion
Using ttk.Notebook
, you can easily create tabbed interfaces in Python. Try customizing the tabs to add more functionality!
Comments
Post a Comment
hello