Monitor System Performance using ttkbootstrap Meter and psutil in Tkinter

Monitoring different Process by using psutil and ttkbootstrap Meter

Introduction

In this tutorial, we will use ttkbootstrap meters along with psutil to display real-time system performance, including:

Monitoring System Resources with psutil in Python

The psutil (python system and process utilities) library in Python provides an interface for retrieving system information, such as CPU usage, memory consumption, disk usage, network statistics, and running processes. It is widely used for system monitoring, performance analysis, and resource management in applications.

Visit Documentation

Setting Up Dependencies

# Install required libraries if not already installed
pip install ttkbootstrap psutil

Code Breakdown

1. Importing Required Libraries

# Import necessary libraries
import psutil
import ttkbootstrap as tb
import time, threading
  • psutil: Fetches system performance metrics.
  • ttkbootstrap: Provides enhanced Tkinter widgets.
  • threading: Runs background tasks without freezing the GUI.

2. Function to Change Color Dynamically

# Function to assign colors based on usage levels
def get_bootstyle(value):
    if value <= 30:  
        return "success"  
    elif value <= 70:  
        return "warning"  
    else:  
        return "danger"
  • Green (success): Usage ≤ 30%
  • Yellow (warning): Usage 31% - 70%
  • Red (danger): Usage ≥ 71%

3. Creating the Tkinter Window

# Create main application window
root = tb.Window(themename="superhero")
root.title("System Performance Monitor")

1. CPU Usage Meter 🔝


Monitoring CPU uses by using psutil and ttkbootstrap Meter

1. Function to Update the CPU Meter

def update_meter():
    while True:
        cpu_usage = psutil.cpu_percent(interval=1)
        meter.configure(amountused=cpu_usage, bootstyle=get_bootstyle(cpu_usage))
        root.update_idletasks()
        time.sleep(1)
  • psutil.cpu_percent(): Fetches the current CPU usage.
  • meter.configure(): Updates the meter with the new value.
  • root.update_idletasks(): Ensures UI updates smoothly.

2. Creating the CPU Meter

# Creating the CPU usage meter
meter = tb.Meter(
    root, bootstyle="success", subtext="CPU Usage", amounttotal=100, interactive=False
)
meter.pack(pady=20)
  • bootstyle="success": Initial color of the meter.
  • amounttotal=100: The meter represents 100% usage.
  • interactive=False: Disables user interaction.

3. Running the Update Function in a Thread

# Run the update function in a separate thread
threading.Thread(target=update_meter, daemon=True).start()
  • threading.Thread(): Runs `update_meter` in a background thread.
  • daemon=True: Ensures the thread stops when the app is closed.

Real-Time CPU Usage Monitor with Python psutil , Tkinter, and ttkbootstrap #psutil #cupmonitor

import psutil
import ttkbootstrap as tb
import time
import threading

def get_bootstyle(value):
    if value <= 30:
        return "success"
    elif value <= 70:
        return "warning"
    else:
        return "danger"

def update_meter():
    while True:
        cpu_usage = psutil.cpu_percent(interval=1)
        meter.configure(amountused=cpu_usage, bootstyle=get_bootstyle(cpu_usage))
        root.update_idletasks()
        time.sleep(1)

root = tb.Window(themename="superhero")
root.title("CPU Usage Monitor")

meter = tb.Meter(
    root, bootstyle="success", subtext="CPU Usage", amounttotal=100, interactive=False
)
meter.pack(pady=20)

threading.Thread(target=update_meter, daemon=True).start()
root.mainloop()

2. RAM Usage Meter 🔝


Monitoring RAM uses by using psutil and ttkbootstrap Meter

1. Function to Update the RAM Meter

def update_ram_meter():
    while True:
        ram_usage = psutil.virtual_memory().percent
        ram_meter.configure(amountused=ram_usage, bootstyle=get_bootstyle(ram_usage))
        root.update_idletasks()
        time.sleep(1)
  • psutil.virtual_memory().percent: Fetches the current RAM usage percentage.
  • ram_meter.configure(): Updates the meter with the new RAM usage value.
  • root.update_idletasks(): Ensures UI updates smoothly.

2. Creating the RAM Meter

# Creating the RAM usage meter
ram_meter = tb.Meter(
    root, bootstyle="success", subtext="RAM Usage", amounttotal=100, interactive=False
)
ram_meter.pack(pady=20)
  • bootstyle="success": Initial color of the meter.
  • amounttotal=100: The meter represents 100% usage.
  • interactive=False: Disables user interaction.

3. Running the Update Function in a Thread

# Run the RAM update function in a separate thread
threading.Thread(target=update_ram_meter, daemon=True).start()
  • threading.Thread(): Runs `update_ram_meter` in a background thread.
  • daemon=True: Ensures the thread stops when the app is closed.

import psutil
import ttkbootstrap as tb
import time
import threading

def get_bootstyle(value):
    if value <= 30:
        return "success"
    elif value <= 70:
        return "warning"
    else:
        return "danger"

def update_meter():
    while True:
        ram_usage = psutil.virtual_memory().percent
        meter.configure(amountused=ram_usage, bootstyle=get_bootstyle(ram_usage))
        root.update_idletasks()
        time.sleep(1)

root = tb.Window(themename="flatly")
root.title("RAM Usage Monitor")

meter = tb.Meter(
    root, bootstyle="success", subtext="RAM Usage", amounttotal=100, interactive=False
)
meter.pack(pady=20)

threading.Thread(target=update_meter, daemon=True).start()
root.mainloop()

3. Disk Usage Meter 🔝


Monitoring Disk  uses by using psutil and ttkbootstrap Meter

1. Function to Update the Disk Meter

def update_disk_meter():
    while True:
        disk_usage = psutil.disk_usage('/').percent
        disk_meter.configure(amountused=disk_usage, bootstyle=get_bootstyle(disk_usage))
        root.update_idletasks()
        time.sleep(2)
  • psutil.disk_usage('/'): Fetches the current disk usage percentage.
  • disk_meter.configure(): Updates the meter with the new disk usage value.
  • root.update_idletasks(): Ensures UI updates smoothly.

2. Creating the Disk Meter

# Creating the Disk usage meter
disk_meter = tb.Meter(
    root, bootstyle="success", subtext="Disk Usage", amounttotal=100, interactive=False
)
disk_meter.pack(pady=20)
  • bootstyle="success": Initial color of the meter.
  • amounttotal=100: The meter represents 100% usage.
  • interactive=False: Disables user interaction.

3. Running the Update Function in a Thread

# Run the Disk update function in a separate thread
threading.Thread(target=update_disk_meter, daemon=True).start()
  • threading.Thread(): Runs `update_disk_meter` in a background thread.
  • daemon=True: Ensures the thread stops when the app is closed.

import psutil
import ttkbootstrap as tb
import time
import threading

def get_bootstyle(value):
    if value <= 30:
        return "success"
    elif value <= 70:
        return "warning"
    else:
        return "danger"

def update_disk_meter():
    while True:
        disk_usage = psutil.disk_usage('/').percent
        meter.configure(amountused=disk_usage, bootstyle=get_bootstyle(disk_usage))
        root.update_idletasks()
        time.sleep(2)

root = tb.Window(themename="solar")
root.title("Disk Usage Monitor")

meter = tb.Meter(
    root, bootstyle="success", subtext="Disk Usage", amounttotal=100, interactive=False
)
meter.pack(pady=20)

threading.Thread(target=update_disck_meter, daemon=True).start()
root.mainloop()

4. Network Speed Meter 🔝


Monitoring Network speed  by using psutil and ttkbootstrap Meter

1. Function to Update the Network Meter

def update_meter():
    old_value = psutil.net_io_counters().bytes_recv
    while True:
        new_value = psutil.net_io_counters().bytes_recv
        speed = (new_value - old_value) / 1024  # Convert bytes to KB/s
        speed = round(speed, 2)  # Format to 2 decimal places
        old_value = new_value
        meter.configure(amountused=min(speed, 100), 
                        subtext=f"Speed: {speed} KB/s", 
                        bootstyle=get_bootstyle(min(speed, 100)))
        root.update_idletasks()
        time.sleep(1)
  • psutil.net_io_counters().bytes_recv: Fetches the total received bytes.
  • speed = (new_value - old_value) / 1024: Calculates the download speed in KB/s.
  • network_meter.configure(): Updates the meter with the new network speed value.
  • root.update_idletasks(): Ensures UI updates smoothly.

2. Creating the Network Speed Meter

# Creating the Network speed meter
network_meter = tb.Meter(
    root, bootstyle="success", subtext="Download Speed (KB/s)", amounttotal=100, interactive=False
)
network_meter.pack(pady=20)
  • bootstyle="success": Initial color of the meter.
  • amounttotal=100: The meter represents 100 KB/s as the maximum value.
  • interactive=False: Disables user interaction.

3. Running the Update Function in a Thread

# Run the Network update function in a separate thread
threading.Thread(target=update_network_meter, daemon=True).start()
  • threading.Thread(): Runs `update_network_meter` in a background thread.
  • daemon=True: Ensures the thread stops when the app is closed.

import psutil
import ttkbootstrap as tb
import time
import threading

def get_bootstyle(value):
    if value <= 30:
        return "success"
    elif value <= 70:
        return "warning"
    else:
        return "danger"

def update_network_meter():
    old_value = psutil.net_io_counters().bytes_recv
    while True:
        new_value = psutil.net_io_counters().bytes_recv
        speed = (new_value - old_value) / 1024  # KB/s
        speed = round(speed, 2)  # Format to 2 decimal places
        old_value = new_value
        meter.configure(amountused=min(speed, 100), bootstyle=get_bootstyle(min(speed, 100)))
        root.update_idletasks()
        time.sleep(1)

root = tb.Window(themename="darkly")
root.title("Network Speed Monitor")

meter = tb.Meter(
    root, bootstyle="success", subtext="Download Speed (KB/s)", amounttotal=100, interactive=False
)
meter.pack(pady=20)

threading.Thread(target=update_network_meter, daemon=True).start()
root.mainloop()

5. Battery Percentage Meter 🔝


Monitoring CPU uses by using psutil and ttkbootstrap Meter

1. Function to Update the Battery Meter

def update_battery_meter():
    while True:
        battery = psutil.sensors_battery()
        if battery:
            battery_percent = battery.percent
            battery_meter.configure(amountused=battery_percent, bootstyle=get_bootstyle(battery_percent))
        root.update_idletasks()
        time.sleep(10)  # Update every 10 seconds
  • psutil.sensors_battery(): Fetches the battery status.
  • battery.percent: Retrieves the current battery percentage.
  • battery_meter.configure(): Updates the meter with the new battery percentage.
  • root.update_idletasks(): Ensures UI updates smoothly.

2. Creating the Battery Percentage Meter

# Creating the Battery percentage meter
battery_meter = tb.Meter(
    root, bootstyle="success", subtext="Battery Level", amounttotal=100, interactive=False
)
battery_meter.pack(pady=20)
  • bootstyle="success": Initial color of the meter.
  • amounttotal=100: The meter represents 100% battery level.
  • interactive=False: Disables user interaction.

3. Running the Update Function in a Thread

# Run the Battery update function in a separate thread
threading.Thread(target=update_battery_meter, daemon=True).start()
  • threading.Thread(): Runs `update_battery_meter` in a background thread.
  • daemon=True: Ensures the thread stops when the app is closed.

import psutil
import ttkbootstrap as tb
import time
import threading

def get_bootstyle(value):
    if value >= 70:
        return "success"
    elif value >= 30:
        return "warning"
    else:
        return "danger"

def update_battery_meter():
    while True:
        battery = psutil.sensors_battery()
        if battery:
            percent = battery.percent
            meter.configure(amountused=percent, bootstyle=get_bootstyle(percent))
        root.update_idletasks()
        time.sleep(10)

root = tb.Window(themename="minty")
root.title("Battery Monitor")

meter = tb.Meter(
    root, bootstyle="success", subtext="Battery Level", amounttotal=100, interactive=False
)
meter.pack(pady=20)

threading.Thread(target=update_battery_meter, daemon=True).start()
root.mainloop()

Running the Tkinter Loop

root.mainloop()

Combine System Performance Monitor 🔝

This script displays CPU, RAM, Disk, Network Speed, and Battery usage using stylish circular meters with dynamic colors that change based on usage levels. The meters are arranged in a grid layout with three rows, ensuring a clean and structured UI.

Key Highlights of the Combined Application

This final integrated application efficiently combines all five process parameters into a single interface while maintaining a consistent look and feel. Here’s how:

  • Consistent Bootstrap Styling: A unified Bootstrap theme ensures a clean and professional UI across all meters.
  • Threading for Smooth Performance: Threading is implemented to keep the application responsive while fetching real-time system data.
  • Uniform Meter Scaling: Each meter is set with amounttotal=100, ensuring a standardized percentage-based display for easy comparison.

This structured approach improves readability, performance, and user experience, making the app more efficient and visually appealing.


import psutil
import ttkbootstrap as tb
import time
import threading

# Function to assign bootstyle color based on usage levels
def get_bootstyle(value):
    if value <= 30:
        return "success"
    elif value <= 70:
        return "warning"
    else:
        return "danger"

# Function to update CPU meter
def update_cpu_meter():
    while True:
        cpu_usage = psutil.cpu_percent(interval=1)
        cpu_meter.configure(amountused=cpu_usage, bootstyle=get_bootstyle(cpu_usage))
        root.update_idletasks()
        time.sleep(1)

# Function to update RAM meter
def update_ram_meter():
    while True:
        ram_usage = psutil.virtual_memory().percent
        ram_meter.configure(amountused=ram_usage, bootstyle=get_bootstyle(ram_usage))
        root.update_idletasks()
        time.sleep(1)

# Function to update Disk meter
def update_disk_meter():
    while True:
        disk_usage = psutil.disk_usage('/').percent
        disk_meter.configure(amountused=disk_usage, bootstyle=get_bootstyle(disk_usage))
        root.update_idletasks()
        time.sleep(2)

# Function to update Network Speed meter
def update_network_meter():
    old_value = psutil.net_io_counters().bytes_recv
    while True:
        new_value = psutil.net_io_counters().bytes_recv
        speed = (new_value - old_value) / 1024  # Convert to KB/s
        speed = round(speed, 2)  # Format to 2 decimal places
        old_value = new_value
        network_meter.configure(amountused=min(speed, 100), subtext=f"Speed: {speed} KB/s", bootstyle=get_bootstyle(speed))
        root.update_idletasks()
        time.sleep(1)

# Function to update Battery meter
def update_battery_meter():
    while True:
        battery = psutil.sensors_battery()
        if battery:
            battery_percent = battery.percent
            battery_meter.configure(amountused=battery_percent, bootstyle=get_bootstyle(battery_percent))
        root.update_idletasks()
        time.sleep(10)

# Creating the main Tkinter window
root = tb.Window(themename="superhero")
root.title("System Performance Monitor")

# Configure grid layout
root.columnconfigure(0, weight=1)  
root.columnconfigure(1, weight=1)  

# Headline at the top right
headline = tb.Label(root, text="🔹 System Performance Monitor 🔹", font=("Arial", 16, "bold"), bootstyle="primary")
headline.grid(row=0, column=0, columnspan=2, sticky="e", padx=20, pady=10)

# Row 1: CPU & RAM
cpu_meter = tb.Meter(root, bootstyle="success", subtext="CPU Usage", amounttotal=100, interactive=False)
cpu_meter.grid(row=1, column=0, padx=20, pady=20)

ram_meter = tb.Meter(root, bootstyle="success", subtext="RAM Usage", amounttotal=100, interactive=False)
ram_meter.grid(row=1, column=1, padx=20, pady=20)

# Row 2: Disk & Network Speed
disk_meter = tb.Meter(root, bootstyle="success", subtext="Disk Usage", amounttotal=100, interactive=False)
disk_meter.grid(row=2, column=0, padx=20, pady=20)

network_meter = tb.Meter(root, bootstyle="success", subtext="Download Speed (KB/s)", amounttotal=100, interactive=False)
network_meter.grid(row=2, column=1, padx=20, pady=20)

# Row 3: Battery (Centered across two columns)
battery_meter = tb.Meter(root, bootstyle="success", subtext="Battery Level", amounttotal=100, interactive=False)
battery_meter.grid(row=3, column=0, columnspan=2, padx=20, pady=20)

# Running each function in a separate thread
threading.Thread(target=update_cpu_meter, daemon=True).start()
threading.Thread(target=update_ram_meter, daemon=True).start()
threading.Thread(target=update_disk_meter, daemon=True).start()
threading.Thread(target=update_network_meter, daemon=True).start()
threading.Thread(target=update_battery_meter, daemon=True).start()

# Running the Tkinter event loop
root.mainloop()

Combine 5 Powerful Widgets in Python Tkinter with Ttkbootstrap & psutil #tkinter #ttkbootstrap

Why Threading is Important in This Script?

Threading plays a crucial role in ensuring that the application's UI remains responsive while fetching system performance data. Without threading, the main Tkinter loop would be blocked during data retrieval, causing the interface to freeze or lag. To truly understand its impact, try removing the threading implementation and observe how the app responds. You’ll notice a significant difference in performance and responsiveness.

More about Threading
While threading keeps the UI responsive, some widget updates might not appear instantly. Using root.update_idletasks() ensures immediate reflection of changes in all widgets.
More about root.update_idletasks()

Conclusion

With `psutil` and `ttkbootstrap`, we can create visually appealing and real-time system monitoring tools in Python.



Ttkbootstrap Meter bootstyle option using range Two Interlinked Meters Displaying number of chars entered in Text widget using Meter
ttkbootstrap ttkbootstrap Meter Countdown Timer using ttkbootstrap Meter Typing speed test

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer