JustToThePoint English Website Version
JustToThePoint en español
JustToThePoint in Thai

Currency converter. Help windows for key bindings.

Give me six hours to chop down a tree and I will spend the first four sharpening the axe, Abraham Lincoln.

Currency converter

Currency converter

We are going to make use of CurrencyConverter, a currency converter using the European Central Bank data. You need to install its package: pip install CurrencyConverter

from currency_converter import CurrencyConverter

def get_exchange_rate(base_currency, base_currency_symbol, target_currency, target_currency_symbol):
    """
    Fetches the exchange rate from base_currency to target_currency.
    Args: 
    1. base_currency (string): The base currency code, e.g., "EUR".
    2. base_currency_symbol (string): The symbol for the base currency, e.g., "€".
    3. target_currency (string): The target currency code, e.g., "USD".
    4. target_currency_symbol (str): The symbol for the target currency, e.g., "$".
    Example usage: Convert from EUR to USD, get_exchange_rate("EUR", "€", "USD", "$")
    """
    # Load the packaged data (might not be up to date)
    c = CurrencyConverter()

    # Convert 100 units of base currency to target currency
    rate = round(c.convert(100, base_currency, target_currency),2)
    if rate is not None:
        print(f"100{base_currency_symbol} = {rate}{target_currency_symbol}. ", end=" ")
    else:
        print("Could not fetch the exchange rate.")
    
def get_exchange_rates():
    """
    Fetches exchange rates for specific currency pairs.
    Usage: get_exchange_rates()
    """
    get_exchange_rate("EUR", "€", "USD", "$") # EUR to USD
    get_exchange_rate("EUR", "€", "GBP", "£") # EUR to GBP
    get_exchange_rate("EUR", "€", "THB", "฿") # EUR to THB
    get_exchange_rate("THB", "฿", "EUR", "€") # THB to EUR

Help windows for key bindings

Awesome is a highly configurable tiling window manager for X that uses lua. It manages windows in different layouts, like floating or tiled. If you pres Mod4 + s, it displays a help window with all currently assigned key binding from its configuration file.

Creating a help screen similar to AwesomeWM but for i3 or other window manager using Python can be an efficient way to have quick access to keybindings, commands, aliases, etc.

{
    "Essentials": [
        "$mod+Enter: Open a new terminal.",
        "$mod+b: pavucontrol (sound)",
        "$mod+d: Rofi.",
        "$mod+p: Take a screenshot (requires scrot).",
        "mod+Shift+e: Shutdown.",
        "$mod+r: mode \"resize\""
    ],
    "Basic Navigation": [
        "$mod+j: Focus left.",
        "$mod+k: Focus down.",
        "$mod+l: Focus up.",
        "$mod+;: Focus right."
    ], [...],
    "Window Management": [
        "$mod+Shift+q: Close the focused window.",
        "$mod+f: Toggle fullscreen mode for the focused window.",
        "$mod+Shift+space: Toggle floating mode for the focused window.",
        "$mod+h: Split horizontally.",
        "$mod+v: Split vertically.",
        "$mod+s: Stacking layout.",
        "$mod+w: Tabbed layout.",
        "$mod+e: Toggle between split and tabbed/stacking layout.",
        "$mod+r: Enter resize mode (use j, k, l, ; to resize)."
    ]   
}
'''
File: displayKeybindings.py
Author: Máximo Núñez Alarcón
Description: Awesome's clone of its help window with all currently assigned key binding from its configuration file.
Usage: Edit your i3 configuration file and add the following line:
bindsym $mod+Shift+h exec bash -c 'source /your/Path/venv/bin/activate && python /your/Path/displayKeybindings.py'
After reloading i3, press $mod+Shift+h.
'''

# Import necessary libraries
from dotenv import load_dotenv # Module for loading environment variables from .env file
import os # Module providing a portable way to use operating system-dependent functionality
import tkinter as tk # GUI toolkit: sudo pacman -S tk (Linux, Arch)
from tkinter import scrolledtext # Widget for displaying text with scrolling capabilities
from tkinter import ttk # Themed widget set for tkinter
import json # Module for parsing JSON data

def load_content(file_path):
    """
    Load content from a JSON file.

    Parameters:
        file_path (str): Path to the JSON file.

    Returns:
        dict: Contents of the JSON file as a dictionary.
    """
    with open(file_path, 'r') as file:
        return json.load(file)

def populate_tabs(tab_control, root):
    """
    Populate tabs with content from a JSON file.

    Parameters:
        tab_control (ttk.Notebook): Notebook widget to contain multiple tabs.
        root (tk.Tk): Root window of the application.
    """

    # Path to the JSON file containing keybindings information
    file_path = "/home/nmaximo7/myPython/assets/keybindings.json"  # Change this to your file path
    content = load_content(file_path)
    
    # Iterate over each section in the JSON file
    ''' This is a typical section.
     "Basic Navigation": [
        "$mod+j: Focus left.",
        "$mod+k: Focus down.",
        "$mod+l: Focus up.",
        "$mod+;: Focus right."
    ],
    '''
    for section_title, section_content in content.items():
        tab = ttk.Frame(tab_control) # Create a new tab

        # Add tab to the notebook where section_title is the title of the tab, e.g., "Basic Navigation"
        tab_control.add(tab, text=section_title)  
        
        text_box = tk.Text(tab, wrap="word", font=("Helvetica", 28)) # Create text box with custom font
        text_box.pack(fill="both", expand=True, padx=20, pady=5) # Pack text box into the tab with padding
        
        # Insert content into the text box
        if isinstance(section_content, list): # If section_content is a list.
            for line in section_content:
                text_box.insert("end", line + "\n")  # Insert each line followed by a newline
        elif isinstance(section_content, str): # If section_content is a string.
            text_box.insert("end", section_content) 

        # Add a button to close the window in the last tab
        if section_title == list(content.keys())[-1]:
            close_label = tk.Label(tab, text="Click here to close", fg="blue", cursor="hand2")
            close_button = ttk.Button(tab, text="Click to Close", command=lambda root=root: on_close(root))
            close_button.pack()

def on_close(root):
    """
    Handle window close event by destroying the root window.

    Parameters:
        root (tk.Tk): Root window of the application.
    """
    root.destroy()

# Main function. It displays the keybindings, aliases, and useful commands in a Tkinter window
def show_i3_keybindings(filepath='./assets/keybindings.txt'):
    """
    Display keybindings in a Tkinter window.

    Parameters:
        filepath (str): Path to the keybindings file.
    """

    # Create a Tkinter window
    root = tk.Tk()
    root.title("Tabbed Text Viewer")

    # Create a notebook widget to contain the tabs
    tab_control = ttk.Notebook(root)
    tab_control.pack(expand=1, fill="both")

    # Attach protocol to handle window close event
    root.protocol("WM_DELETE_WINDOW", lambda: on_close(root))

    # Populate tabs with content
    populate_tabs(tab_control, root)
    
    # Run the Tkinter main loop
    root.mainloop()

# Entry point of the program
if __name__ == '__main__':
    load_dotenv() # Load environment variables from .env file
    mypath = os.getenv("KEYBINDING")
    show_i3_keybindings(mypath)
# It sources the virtual environment and then executes the Python script.
bindsym $mod+Shift+h exec bash -c 'source /home/nmaximo7/myPython/venv/bin/activate && python /home/nmaximo7/myPython/displayKeybindings.py'
Bitcoin donation

JustToThePoint Copyright © 2011 - 2024 Anawim. ALL RIGHTS RESERVED. Bilingual e-books, articles, and videos to help your child and your entire family succeed, develop a healthy lifestyle, and have a lot of fun. Social Issues, Join us.

This website uses cookies to improve your navigation experience.
By continuing, you are consenting to our use of cookies, in accordance with our Cookies Policy and Website Terms and Conditions of use.