Vertical Tabs (Python Programming)
Learn Vertical Tabs (Python Programming) step by step with clear examples and exercises.
Why This Matters
Vertical tabs are essential in creating efficient and organized interfaces for both web applications and desktop utilities. They help users navigate through multiple sections or data sets by providing a compact, easily-accessible layout. In this lesson, we'll learn how to create vertical tabs using Python and the popular Tkinter library.
Prerequisites
To follow along with this tutorial, you should have a basic understanding of:
- Python syntax and data structures (variables, functions, lists, dictionaries)
- Familiarity with the Tkinter library for building graphical user interfaces in Python
- Knowledge of how to fetch data from external APIs like Yahoo Finance using libraries such as
requestsandBeautifulSoup
Core Concept
In this section, we'll discuss the core concepts behind creating vertical tabs using Python and Tkinter. We'll cover:
- Creating a basic Tkinter window
- Adding a Notebook widget for our vertical tabs
- Creating individual tabs within the Notebook
- Populating each tab with content
- Fetching data from external APIs and displaying it in tabs
1. Creating a Basic Tkinter Window
To get started, let's create a simple Tkinter window:
import tkinter as tk
root = tk.Tk()
root.title("Vertical Tabs Example")
root.geometry("600x400") # Set the window size
root.mainloop()
This code creates a new Tkinter window, sets its title, and starts the main event loop that handles user interactions.
2. Adding a Notebook Widget for our Vertical Tabs
To create vertical tabs, we'll use the Notebook widget provided by Tkinter:
notebook = tk.Notebook(root)
notebook.pack(fill="both", expand=True)
The above code creates a new Notebook widget and packs it into our main window, filling both the width and height of the window.
3. Creating Individual Tabs within the Notebook
Next, let's create individual tabs inside the Notebook:
tab1 = tk.Frame(notebook)
tab2 = tk.Frame(notebook)
notebook.add(tab1, text="Tab 1")
notebook.add(tab2, text="Tab 2")
In the example above, we create two empty Frame widgets for our tabs and add them to the Notebook with specific labels ("Tab 1" and "Tab 2").
4. Populating Each Tab with Content
Now that we have our tabs set up, let's populate each tab with some content:
def create_content(tab):
label = tk.Label(tab, text="This is the content for this tab.")
label.pack(fill="both", expand=True)
create_content(tab1)
create_content(tab2)
The create_content() function takes a Frame widget as an argument and adds a simple Label with some text to that frame. We call this function for both our tabs, resulting in the following output:
5. Fetching Data from External APIs and Displaying it in Tabs
To make our vertical tabs more useful, let's fetch data from an external API like Yahoo Finance and display it in separate tabs:
import requests
from bs4 import BeautifulSoup
import json
import tkinter as tk
from urllib.parse import urlencode
def get_stock_prices(symbols):
params = {"q": ",".join(symbols), "fmt": "json"}
response = requests.get("https://query1.finance.yahoo.com/v7/finance/download", params=params)
data = json.loads(response.text)["quoteSummary"]["result"][0]["history"]["time"] + [data["history"]["time"][-1]["at"]]
prices = []
for time in data:
price_row = data[data.index(time)]["time"] + " - " + data[data.index(time)]["4. close"]
prices.append(price_row)
return prices
def create_content(tab, symbol):
label = tk.Label(tab, text="Stock Price for {}".format(symbol))
label.pack()
price_data = get_stock_prices(["AAPL", "GOOGL"])
scrollbar = tk.Scrollbar(tab, orient="vertical")
listbox = tk.Listbox(tab, yscrollcommand=scrollbar.set, height=len(price_data))
for index, price in enumerate(price_data):
listbox.insert(index, price)
scrollbar.pack(side="right", fill="y")
listbox.pack(fill="both", expand=True)
root = tk.Tk()
root.title("Stock Prices Example")
root.geometry("600x400") # Set the window size
root.mainloop()
symbols = ["AAPL", "GOOGL"] # List of stock symbols to fetch data for
notebook = tk.Notebook(root)
notebook.pack(fill="both", expand=True)
tab1 = tk.Frame(notebook)
tab2 = tk.Frame(notebook)
notebook.add(tab1, text="Apple (AAPL)")
notebook.add(tab2, text="Google (GOOGL)")
create_content(tab1, symbols[0])
create_content(tab2, symbols[1])
This code fetches stock prices for Apple and Google using the Yahoo Finance API, creates two vertical tabs for each symbol, and populates them with the fetched data:
Worked Example
In this section, we'll create a more complex example that demonstrates how to use vertical tabs for displaying data from multiple external sources. We'll fetch stock prices and weather data and display them in separate tabs:
import requests
from bs4 import BeautifulSoup
import json
import tkinter as tk
from urllib.parse import urlencode
def get_stock_prices(symbols):
params = {"q": ",".join(symbols), "fmt": "json"}
response = requests.get("https://query1.finance.yahoo.com/v7/finance/download", params=params)
data = json.loads(response.text)["quoteSummary"]["result"][0]["history"]["time"] + [data["history"]["time"][-1]["at"]]
prices = []
for time in data:
price_row = data[data.index(time)]["time"] + " - " + data[data.index(time)]["4. close"]
prices.append(price_row)
return prices
def get_weather_data():
response = requests.get("http://api.openweathermap.org/data/2.5/weather", params={"q": "New York,us", "appid": "YOUR_API_KEY"})
data = json.loads(response.text)
temp = data["main"]["temp"] - 273.15 # Convert from Kelvin to Celsius
description = data["weather"][0]["description"]
return f"Temperature: {temp:.1f}°C\nDescription: {description}"
def create_content(tab, symbol):
if symbol == "Weather":
content = get_weather_data()
else:
price_data = get_stock_prices([symbol])
scrollbar = tk.Scrollbar(tab, orient="vertical")
listbox = tk.Listbox(tab, yscrollcommand=scrollbar.set, height=len(price_data))
for index, price in enumerate(price_data):
listbox.insert(index, price)
scrollbar.pack(side="right", fill="y")
listbox.pack(fill="both", expand=True)
root = tk.Tk()
root.title("Data Example")
root.geometry("600x400") # Set the window size
root.mainloop()
symbols = ["AAPL", "GOOGL"]
weather_tab = tk.Frame(root)
notebook = tk.Notebook(root)
notebook.add(tk.Frame(root), text="Stock Prices")
for symbol in symbols:
notebook.add(tk.Frame(root), text=symbol)
notebook.add(weather_tab, text="Weather")
notebook.pack(fill="both", expand=True)
create_content(notebook.tab(0)[1], "Stock Prices") # Set content for the first tab
for index, symbol in enumerate(symbols):
create_content(notebook.tab(index+2)[1], symbol) # Set content for each stock tab
create_content(weather_tab, "Weather") # Set content for the weather tab
This code fetches stock prices and weather data from external APIs, creates three vertical tabs for each symbol, and populates them with the fetched data:
Common Mistakes
- Forgetting to call
mainloop(): The main event loop is crucial for handling user interactions in Tkinter applications. Without it, the window will not respond to clicks or other events.
- Not packing or grid-placing widgets properly: Ensure that all widgets are packed or grid-placed within their parent widget to ensure proper layout and positioning.
- Ignoring Tkinter's event loop: Always write event handlers for user interactions like clicks, key presses, etc., by defining functions and binding them to the appropriate events using
bind().
Practice Questions
- Modify the example above to fetch data for multiple symbols (e.g., AAPL, GOOGL, MSFT). Create a new tab for each symbol, with the number of tabs matching the number of symbols provided.
- Add a search field that allows users to enter stock symbols and dynamically create/display tabs based on their input.
- Implement retry logic when fetching data from external APIs to handle temporary network issues or API rate limits.
FAQ
Q: How can I customize the appearance of my vertical tabs in Tkinter?
A: You can customize the appearance of your tabs by creating a ttk::Notebook instance instead of the default Notebook. Then, use the tabstyle option to set a custom style for your tabs.
Q: How do I handle errors when fetching data from external APIs like Yahoo Finance?
A: You can wrap the API call in a try-except block to catch any exceptions and display an error message to the user. Additionally, you may want to implement retry logic for certain types of errors (e.g., network issues) to ensure that your application remains responsive.
Q: How do I fetch data from multiple APIs simultaneously?
A: To fetch data from multiple APIs at once, consider using Python's concurrent.futures module and its ThreadPoolExecutor or ProcessPoolExecutor classes to execute API calls concurrently. This can help improve the performance of your application when dealing with multiple data sources.