How to Create a Bar Chart In Python Tkinter
In this Python tutorial we will create a Bar Chart with alternating colors for the bars using the Tkinter library for the graphical user interface.
What We Are Gonna Use In This Project:
- Python Programming Language.- Tkinter for GUI.
- VS Code Editor.
- VS Code Editor.
Project Source Code:
import tkinter as tk
class BarChartPanel(tk.Canvas):
def __init__(self, master=None, **kwargs):
# Initialize the BarChartPanel as a Canvas
super().__init__(master, **kwargs)
self.use_orange_color = False # Flag to alternate between gradient colors
# Create the bar chart
self.create_barchart()
def create_barchart(self):
# Sample data for the bar chart
values = [30, 50, 70, 40, 60, 130, 50, 70, 40, 60]
labels = ["A", "B", "C", "D", "E", "A2", "B2", "C2", "D2", "E2"]
max_value = 130
# Get dimensions for the chart
chart_width = self.winfo_reqwidth()
chart_height = self.winfo_reqheight()
# Calculate bar width and spacing
bar_spacing = 20
bar_width = (chart_width - (len(values) + 1) * bar_spacing) // len(values)
# Draw horizontal lines for reference
num_horizontal_lines = 5
horizontal_spacing = (chart_height - 50) // num_horizontal_lines
# Draw horizontal reference lines
for i in range(num_horizontal_lines + 1):
y = chart_height - 20 - i * horizontal_spacing
self.create_line(30, y, chart_width - 20, y, fill="lightgray",
dash=(2, 2))
# Draw vertical lines for reference
for i in range(len(values)):
x = 30 + i * (bar_width + bar_spacing)
self.create_line(x + bar_width, 20, x + bar_width, chart_height - 20,
fill="lightgray", dash=(2, 2))
# Draw the bars and labels
for i in range(len(values)):
bar_height = int((values[i] / max_value) * (chart_height - 50))
x = 30 + i * (bar_width + bar_spacing)
y = chart_height - bar_height - 20
# Alternate between gradient colors
if self.use_orange_color:
color = "#FF8C00" # Orange color
else:
color = "#3498db" # Blue color
# Draw the rectangle representing the bar
self.create_rectangle(x, y, x + bar_width, y + bar_height, outline="green"
, fill=color, width=2)
# Draw the label for the bar
self.create_text(x + bar_width // 2, chart_height - 5, text=labels[i],
fill="black")
# Toggle the flag for color alternation
self.use_orange_color = not self.use_orange_color
# Draw the vertical axis labels
num_ticks = 5
tick_spacing = (chart_height - 50) / num_ticks
# Draw vertical reference lines
for i in range(num_ticks + 1):
tick_value = int(max_value * i / num_ticks)
tick_label = str(tick_value)
label_x = 10
label_y = chart_height - 20 - i * tick_spacing
self.create_text(label_x, label_y, text=tick_label, fill="black",
anchor=tk.W)
def main():
# Entry point for the application
root = tk.Tk()
root.title("Bar Chart")
root.geometry("650x450")
# Create and pack the BarChartPanel
chart_panel = BarChartPanel(root, width=600, height=400, background="white")
chart_panel.pack(fill=tk.BOTH, expand=True)
root.mainloop()
if __name__ == "__main__":
main()
Aucun commentaire:
Enregistrer un commentaire