Python Tkinter Donut Chart

How to Create a Donut Chart In Python Tkinter

How to Create a Donut Chart In Python Tkinter


In this Python tutorial we will create a donut chart using the Tkinter library for the graphical user interface. 
The chart represents data slices with different colors and includes a legend to describe each slice.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter for GUI.
- VS Code Editor.




Project Source Code:


import tkinter as tk
from tkinter import Canvas


class DonutChart(tk.Tk):
def __init__(self):
# Initialize the Tkinter application
super().__init__()
self.title("Donut Chart")
self.geometry("550x400")

# Create and pack the DonutChartPanel
self.donut_chart_panel = DonutChartPanel(self)
self.donut_chart_panel.pack(fill=tk.BOTH, expand=True)

# Start the Tkinter main loop
self.mainloop()


class DonutChartPanel(Canvas):
def __init__(self, master=None):
# Initialize the DonutChartPanel as a Canvas with a light background color
super().__init__(master, bg="#f0f0f0")
# color palette for the donut slices
self.slice_colors = ["#65AEDD", "#FFB74D", "#66BB6A", "gray"]
# Data for the donut slices
self.data = [40, 30, 20, 10]
# Draw the donut chart
self.draw_donut_chart()

def draw_donut_chart(self):
# Get the width and height of the canvas
width = self.winfo_reqwidth()
height = self.winfo_reqheight()
# Calculate the diameter of the donut chart
diameter = min(width, height) - 20
outer_radius = diameter / 2
inner_radius = outer_radius * 0.5
x = (width - diameter) / 2
y = (height - diameter) / 2
start_angle = 0

# Draw each slice of the donut chart
for i, value in enumerate(self.data):
arc_angle = int(value / 100 * 360)
# Create an arc for the donut slice
self.create_arc(x, y, x + diameter, y + diameter, start = start_angle,
            extent=arc_angle, fill=self.slice_colors[i], outline="black")
start_angle += arc_angle


# Draw the inner circle to create the donut effect
self.create_oval(x + outer_radius - inner_radius, y +
                         outer_radius - inner_radius,
x + outer_radius + inner_radius, y +
                         outer_radius + inner_radius,
fill="#f0f0f0", outline="black")

# Draw legend for each slice
legend_x = width - 110
legend_y = 20

for i, value in enumerate(self.data):
# Draw a rectangle with the slice color in the legend
self.create_rectangle(legend_x + 100, legend_y, legend_x + 120,
            legend_y + 20, fill=self.slice_colors[i])

# Display the legend text with slice number and percentage
self.create_text(legend_x + 130, legend_y + 10,
            text=f"Slice{i+1}:{value}%", anchor=tk.W, fill="#333")

legend_y += 30



if __name__ == "__main__":
DonutChart()


The Final Result:

Python Tkinter Donut Chart












Share this

Related Posts

Previous
Next Post »