Affichage des articles dont le libellé est Python. Afficher tous les articles
Affichage des articles dont le libellé est Python. Afficher tous les articles

Python Pie Chart Using Tkinter

How to Create a Pie Chart In Python Tkinter

How to Create a Pie Chart In Python Tkinter


In this Python tutorial we will create a pie chart using the Tkinter library for the graphical user interface. 
The pie chart displays three slices with predefined colors and values, along with a legend indicating the percentage of 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 PieChart(tk.Tk):
def __init__(self):

super().__init__()
self.title("Pie Chart")
self.geometry("550x400")

# Create the PieChartPanel instance and pack it into the root window
self.pie_chart_panel = PieChartPanel(self)
self.pie_chart_panel.pack(fill=tk.BOTH, expand=True)

self.mainloop()

class PieChartPanel(Canvas):
def __init__(self, master = None):
super().__init__(master, bg="white")
# Define slice colors and data values for the pie chart
self.slice_colors = ["#FEC107", "#2196F3", "#4CAF50"]
self.data = [40, 30, 30]
# Draw the pie chart
self.draw_pie_chart()

def draw_pie_chart(self):
# Get the width and height of the canvas
width = self.winfo_reqwidth()
height = self.winfo_reqheight()
# Calculate the diameter of the pie chart
diameter = min(width, height) - 20
# Calculate the starting position of the pie chart
x = (width - diameter) / 2
y = (height - diameter) / 2
start_angle = 0

# Draw each slice of the pie chart
for i, value in enumerate(self.data):
# Calculate the angle of the current slice
arc_angle = int(value / 100 * 360)
# Draw the arc representing the slice
self.create_arc(x, y, x + diameter, y + diameter, start = start_angle,
            extent=arc_angle, fill=self.slice_colors[i], outline="black", width=2)
# Update the start angle for the next slice
start_angle += arc_angle
# Draw the legend for the pie chart
legend_x = width - 110
legend_y = 20

for i, value in enumerate(self.data):
# Draw colored rectangles representing each slice
self.create_rectangle(legend_x + 100, legend_y, legend_x + 120,
            legend_y + 20, fill=self.slice_colors[i])
# Add text indicating the percentage of each slice
self.create_text(legend_x + 130, legend_y + 10,
            text = f"Slice{i + 1}:{value}%", anchor=tk.W)
legend_y += 30



if __name__ == "__main__":
PieChart()



The Final Result:

Python Pie Chart Using Tkinter








Python Tkinter Animated Chart

How to Create An Animated Chart In Python Tkinter

How to Create An Animated Chart In Python Tkinter


In this Python tutorial we will create an animated bar chart using the Tkinter library for the graphical user interface. 
We will create an animated bar chart that transitions between two datasets over a specified duration.

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, StringVar
from time import sleep

class AnimatedChart(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()

self.months = ["Jan","Feb", "Mar", "Apr", "May"]
self.data1 = [00, 00, 00, 00, 00]
self.data2 = [27, 63, 47, 81, 16]
self.current_data = self.data1
self.animated_data = self.data1.copy()
self.animated_duration = 2000
self.animation_steps = 100
self.step = 0
self.chart_title = "Sales"

self.create_widgets()


def create_widgets(self):
# Create canvas
self.canvas = Canvas(self, width=600, height=450, bg="white")
self.canvas.pack()
# Start animation
self.timer_callback()
def timer_callback(self):
if self.step <= self.animation_steps:
for i in range(len(self.data1)):
# Update animated data based on current step
start_value = self.data1[i]
end_value = self.data2[i]
self.animated_data[i] = start_value + (end_value - start_value) *
                self.step / self.animation_steps

# Increment step and redraw chart
self.step += 1
self.draw_chart()
# Schedule next animation step
self.after(self.animated_duration // self.animation_steps,
            self.timer_callback)

else:
# Switch to the other set of data for the next animation cycle
self.current_data = self.data2 if self.current_data == self.data1
            else self.data1
self.step = 0



def draw_chart(self):
# Clear canvas
self.canvas.delete("all")

# Set chart dimensions
chart_width = 600
chart_height = 400
bar_spacing = 30
bar_width = (chart_width - (len(self.current_data) + 1) * bar_spacing) /
        len(self.current_data)

# Draw chart title
self.canvas.create_text(chart_width // 2, 30, text=self.chart_title,
        font=("Arial", 28, "bold"), fill="blue")

# Draw horizontal grid lines
for i in range(1, 26):
y = chart_height - i * (chart_height - 100) /25 - 20
self.canvas.create_line(bar_spacing, y, chart_width - bar_spacing, y,
            fill="#e0e0e0")


# Draw vertical grid lines
for i in range(len(self.current_data) + 1):
x = bar_spacing + i * (bar_width + bar_spacing) + bar_width / 2
self.canvas.create_line(x, chart_height - 20, x, 80, fill="#e0e0e0")


# Draw bars and labels
for i in range(len(self.current_data)):
bar_height = (self.animated_data[i] / 100) * (chart_height - 100)
x = bar_spacing + i * (bar_width + bar_spacing)
y = chart_height - bar_height - 20

# Draw bar
self.canvas.create_rectangle(x, y, x + bar_width, chart_height - 20,
            fill="#6a1b9a")

# Draw month label
self.canvas.create_text(x + bar_width / 2, chart_height - 5,
            text = self.months[i], font=("Arial", 12), fill="black")
# Draw bar value label
self.canvas.create_text(x + bar_width / 2, y - 10,
            text = str(int(self.animated_data[i])), font=("Arial", 14), fill="black")


if __name__ == "__main__":
root = tk.Tk()
root.title("Animated Chart")
app = AnimatedChart(master=root)
root.mainloop()


The Final Result:

Python Tkinter Animated Chart











Create an Image Slicer Using Python Tkinter

How to Split an Image Into Pieces Using Python Tkinter

How to Split an Image Into Pieces Using Python Tkinter




In this Python Tutorial, we will see how to create an Image Slicer application using python and tkinter.
When a user selects an image and specifies the number of slices, our Python script handles all the functionality including file reading, image processing, and dynamic grid generation.




Project Source Code:



import tkinter as tk
from tkinter import filedialog
from PIL import Image, ImageTk

class ImageSlicer(tk.Tk):
def __init__(self):
super().__init__()
# Set window properties
self.title("Image Slice")
self.geometry("900x500")
self.configure(bg="#fefefe")
# Create main container
self.main_container = tk.Frame(self, bg="#f7f7f7")
self.main_container.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)

# Create top frame for controls
self.control_frame = tk.Frame(self.main_container, bg="#f7f7f7")
self.control_frame.pack(fill=tk.X, pady=(0, 10))

# Create and place the upload button
self.upload_btn = tk.Button(self.control_frame, text="Upload Image",
bg="#2196F3", fg="white",
font=("Arial", 12, "bold"), padx=20, pady=8, bd=0,
command=self.upload_image,
cursor="hand2", activebackground="#1976D2")
self.upload_btn.pack(side=tk.LEFT, padx=5)

# Create spinboxes for rows and columns
self.rows_var = tk.StringVar(value="5")
self.cols_var = tk.StringVar(value="5")

row_frame = tk.Frame(self.control_frame, bg="#f7f7f7")
row_frame.pack(side=tk.LEFT, padx=20)

tk.Label(row_frame, text="Rows", bg="#f7f7f7",
font=("Arial", 12)).pack(side=tk.LEFT)
tk.Spinbox(row_frame, from_=2, to=20, width=5, textvariable=self.rows_var,
font=("Arial", 12)).pack(side=tk.LEFT, padx=5)

col_frame = tk.Frame(self.control_frame, bg="#f7f7f7")
col_frame.pack(side=tk.LEFT)

tk.Label(col_frame, text="Columns", bg="#f7f7f7",
font=("Arial", 12)).pack(side=tk.LEFT)
tk.Spinbox(col_frame, from_=2, to=20, width=5, textvariable=self.cols_var,
font=("Arial", 12)).pack(side=tk.LEFT, padx=5)

# Create frame for slices
self.slices_frame = tk.Frame(self.main_container, bg="#f7f7f7")
self.slices_frame.pack(fill=tk.BOTH, expand=True)

# Store the current image
self.current_image = None


def calculate_image_size(self):
"""Calculate the maximum size for the image to fit in the window"""
# Get window dimensions with padding
padding = 40 # Total padding (20px on each side)
max_width = self.winfo_width() - padding
max_height = self.winfo_height() - self.control_frame.winfo_height() - padding

if self.current_image:
# Get original image dimensions
img_width, img_height = self.current_image.size
# Calculate scaling factor to fit window
width_ratio = max_width / img_width
height_ratio = max_height / img_height
scale_factor = min(width_ratio, height_ratio)

# Calculate new dimensions
new_width = int(img_width * scale_factor)
new_height = int(img_height * scale_factor)

return new_width, new_height
return None

def upload_image(self):
"""Handle image upload and processing"""
file_path = filedialog.askopenfilename(filetypes=[
("Images Files", "*.jpg *.jpeg *.png")])

if file_path:
# Open and store the image
self.current_image = Image.open(file_path)
self.refresh_slices()

def refresh_slices(self):
"""Refresh the image slices with current settings"""
if not self.current_image:
return
# Clear previous slices
for widget in self.slices_frame.winfo_children():
widget.destroy()

# Get number of rows and columns
rows = int(self.rows_var.get())
cols = int(self.cols_var.get())

# Calculate new image size to fit window
new_size = self.calculate_image_size()
if not new_size:
return
# Resize the image
resized_image = self.current_image.resize(new_size, Image.Resampling.LANCZOS)

# Calculate slice dimensions
slice_width = new_size[0] // rows
slice_height = new_size[1] // cols

# Configure grid weights for even distribution
for i in range(rows):
self.slices_frame.grid_rowconfigure(i, weight=1)
for j in range(cols):
self.slices_frame.grid_columnconfigure(j, weight=1)
# Generate and display slices
for i in range(rows):
for j in range(cols):
# Calculate slice coordinates
left = j * slice_width
upper = i * slice_height
right = left + slice_width
lower = upper + slice_height

# Create the slice
slice_image = resized_image.crop((left, upper, right, lower))
tk_image = ImageTk.PhotoImage(slice_image)

# Create and place the label
slice_label = tk.Label(self.slices_frame, image=tk_image,
bg="#f7f7f7", relief="solid", borderwidth=0)
slice_label.image = tk_image
slice_label.grid(row=i, column=j, padx=0, pady=0, sticky="nsew")


if __name__ == "__main__":
app = ImageSlicer()
app.mainloop()



OUTPUT:

Image Slicer Using Python Tkinter

Split Image Into Slices Using Python Tkinter

Create an Image Slicer Using Python Tkinter

Image Slicer App Using Python Tkinter

Image Spliter App Using Python Tkinter

Upload and Slice Image Using Python Tkinter






Python Dashboard Design Using Tkinter

How to Create a Dashboard Form In Python Tkinter

How to Create a Dashboard Form In Python Tkinter


In this Python tutorial we will create a custom dashboard form using the Tkinter library. 
The Dashboard includes a title bar, several data panels, and a bar chart. 
The data panels display financial information such as Sales, Expenses, Profit, and Customers, while the bar chart shows order data for different products.

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 Frame, Label, BOTH, Canvas

class Dashboard:
def __init__(self, root):
self.root = root
self.root.title("Dashboard")
self.root.geometry("780x600")
self.root.configure(bg="#e6e6e6")

self.create_title_bar()
self.create_dashboard()
def create_title_bar(self):
# Create a dark gray title bar
title_bar = Frame(self.root, bg="#333333", height=30)
title_bar.pack(side="top", fill="x")

# Add a white label with the title text "Dashboard"
title_label = Label(title_bar, text="Dashboard", font=("Arial", 16, "bold"),
        fg="#fff", bg="#333")
title_label.pack(side="left", padx=10, pady=5)



def create_dashboard(self):
# Create a light gray dashboard frame
dashboard_frame = Frame(self.root, bg="#f2f2f2")
dashboard_frame.pack(fill=BOTH, expand=True)

# Add data panels with different colors
self.add_data_panel(dashboard_frame, "Sales","$500k", 0, "#a55eea", "#8854d0")
self.add_data_panel(dashboard_frame,"Expenses","$350k",1,"#e74c3c","#c0392b")
self.add_data_panel(dashboard_frame, "Profit","$150k",2,"#2ecc71","#27ae60")
self.add_data_panel(dashboard_frame,"Customers","1,000",3,"#f39c12","#d35400")

# Add a chart panel with a light gray background
chart_panel = Frame(dashboard_frame, bg="#dcdcdc", bd=2, relief="solid")
chart_panel.place(x = 20, y = 20, width=740, height=350)

# Add a title label to the chart panel
chart_title_label = Label(chart_panel, text="Orders",
        font=("Arial", 20, "bold"), fg="#fff", bg="#e74c3c")
chart_title_label.pack(fill="x")

# Add a canvas to the chart panel
chart_canvas = Canvas(chart_panel, bg="#ddd", bd=0)
chart_canvas.pack(fill="both", expand=True)

# Draw Chart
self.draw_chart(chart_canvas)


def add_data_panel(self, parent, title, value, index, bg_color, title_bg_color):
# Create a data panel with a colorful background
data_panel = Frame(parent, bg = bg_color, bd=2, relief="solid")
data_panel.place(x=len(parent.winfo_children()) * 20 + index * 170, y = 400,
        width=170, height=100)

# Add a white title label
title_label = Label(data_panel, text = title, font=("Arial", 20, "bold"),
        fg="#fff", bg=title_bg_color)
title_label.pack(fill="x")

# Add a white value label
value_label = Label(data_panel, text=value, font=("Arial", 24), fg="#fff",
        bg=bg_color)
value_label.pack(fill="x")


def draw_chart(slef, canvas):
data = [100, 200, 150, 300, 250, 350]
max_data_value = max(data)
bar_width = 60
bar_spacing = 55
start_x = 50
start_y = 250

for i, value in enumerate(data):
bar_height = int(value / max_data_value * (start_y - 60))
x = start_x + (bar_width + bar_spacing) * i
y = start_y - bar_height

# Draw a blue rectangle for the chart bar
canvas.create_rectangle(x, y, x + bar_width, start_y, fill="#3498db")
# Add value to the bar
canvas.create_text(x + 30, y - 15, text=str(value), fill="#4b6584",
            font=("Arial", 14, "bold"))
# Add dark gray text for the product label
canvas.create_text(x + 30, start_y + 15, text=f"Product {i + 1}",
            fill="#333", font=("Arial", 12))




if __name__ == "__main__":
root = tk.Tk()
app = Dashboard(root)
root.mainloop()




The Final Result:

Python Dashboard Design Using Tkinter








Python Photo Editor: Create an Image Editor with Tkinter

How to Create an Image Editor Project in Python Using Tkinter

Image Editor Project in Python Using Tkinter


In this Python tutorial, we will see how to create a simple photo editor application using Tkinter for the GUI and the Pillow library for image manipulation
This photo editor application allows users to open an image and apply various editing effects such as blur, grayscale, brightness enhancement, rotation, color inversion, edge detection, and mirroring.
Users can also crop the image interactively.

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 filedialog, simpledialog
# pip install Pillow
from PIL import Image, ImageTk, ImageFilter, ImageEnhance, ImageOps, ImageChops

class PhotoEditorApp:
def __init__(self, root):
self.root = root
self.root.title("Photo Editor")
self.root.geometry("750x450")
self.canvas = tk.Canvas(self.root, bg="white")
self.canvas.pack(fill=tk.BOTH, expand=True)

# Create menu bar
self.menubar = tk.Menu(self.root)
self.root.config(menu = self.menubar)

# Create File menu with Open and Exit options
self.file_menu = tk.Menu(self.menubar, tearoff=0)
self.menubar.add_cascade(label="File", menu = self.file_menu)
self.file_menu.add_command(label = "Open", command = self.open_image)
self.file_menu.add_separator()
self.file_menu.add_command(label = "Exit", command = self.root.quit)

# Create Edit menu with various image manipulation options
self.edit_manu = tk.Menu(self.menubar, tearoff = 0)
self.menubar.add_cascade(label = "Edit", menu=self.edit_manu)
self.edit_manu.add_command(label = "Blur", command = self.apply_blur)
self.edit_manu.add_command(label = "Grayscale", command = self.apply_grayscale)
self.edit_manu.add_command(label = "Enhance Brightness",
        command = self.enhance_brightness)
self.edit_manu.add_command(label = "Rotate", command = self.rotate_image)
self.edit_manu.add_command(label = "Crop", command = self.crop_image)
self.edit_manu.add_command(label = "Invert Colors",
        command = self.inver_colors)
self.edit_manu.add_command(label = "Edge Detection",
        command = self.edge_detection)
self.edit_manu.add_command(label = "Mirror", command = self.mirror_image)
self.edit_manu.add_command(label = "Original State",
        command = self.display_original_state)


# Variables for cropping
self.crop_start_x = None
self.crop_start_y = None
self.crop_rect = None

# Bind events for cropping
self.canvas.bind("<Button-1>", self.start_crop)
self.canvas.bind("<B1-Motion>", self.update_crop)
self.canvas.bind("<ButtonRelease-1>", self.crop_image)



def open_image(self):
# Open a file dialog to select an image file
file_path = filedialog.askopenfilename(filetypes = [("Image Files" ,
        "*.png *.jpg *.jpeg *.bmp *.gif")])

if file_path:
# Open the selected image file using PIL
self.image = Image.open(file_path)
# Save a copy of the original image
self.original_image = self.image.copy()
self.image_tk = ImageTk.PhotoImage(self.image)
# Display the image on the canvas
self.canvas.create_image(0,0, anchor = tk.NW, image=self.image_tk)


def apply_blur(self):
# Apply a blur filter to the image
if self.image:
blurred_image = self.image.filter(ImageFilter.BLUR)
self.display_image(blurred_image)


def apply_grayscale(self):
# Convert the image to grayscale
if self.image:
grayscale_image = self.image.convert("L")
self.display_image(grayscale_image)


def enhance_brightness(self):
# Enhance the brightness of the image
if self.image:
enhancer = ImageEnhance.Brightness(self.image)
enhanced_image = enhancer.enhance(1.5)
self.display_image(enhanced_image)


def rotate_image(self):
# Rotate the image based on user input
if self.image:
degrees = simpledialog.askinteger("Rotate Image",
            "Enter rotation angle(degrees):", parent = self.root)
if degrees:
rotated_image = self.image.rotate(degrees, expand=True)
self.display_image(rotated_image)


def inver_colors(self):
# Invert the colors of the image
if self.image:
inverted_image = ImageOps.invert(self.image)
self.display_image(inverted_image)

def edge_detection(self):
# Apply edge detection filter to the image
if self.image:
edge_detection = self.image.filter(ImageFilter.FIND_EDGES)
self.display_image(edge_detection)


def mirror_image(self):
# Mirror the image horizontally
if self.image:
mirrored_image = ImageOps.mirror(self.image)
self.display_image(mirrored_image)



def start_crop(self, event):
# Record the starting position of the crop
self.crop_start_x = self.canvas.canvasx(event.x)
self.crop_start_y = self.canvas.canvasy(event.y)



def update_crop(self, event):
"""
Update the crop rectangle during mouse motion.

Args:
event: Mouse event containing information about the current mouse position.
"""
# Get current mouse position relative to the canvas
cur_x = self.canvas.canvasx(event.x)
cur_y = self.canvas.canvasy(event.y)

# Delete previous crop rectangle if it exists
if self.crop_rect:
self.canvas.delete(self.crop_rect)

# Create a new crop rectangle based on the starting position
        # and current position
self.crop_rect = self.canvas.create_rectangle(self.crop_start_x,
        self.crop_start_y, cur_x, cur_y, outline="red")




def crop_image(self, event=None):
"""
Crop the image based on the crop rectangle.

Args:
event: Mouse event triggering the crop action (optional).
"""
if self.crop_rect:
# Get current mouse position relative to the canvas
if event:
cur_x = self.canvas.canvasx(event.x)
cur_y = self.canvas.canvasy(event.y)

# Determine the coordinates of the crop rectangle
x1, y1 = min(self.crop_start_x, cur_x), min(self.crop_start_y, cur_y)
x2, y2 = max(self.crop_start_x, cur_x), max(self.crop_start_y, cur_y)

# Crop the image using the determined coordinates
cropped_image = self.image.crop((x1, y1, x2, y2))
self.display_image(cropped_image)

# Delete the crop rectangle
self.canvas.delete(self.crop_rect)
self.crop_rect = None



def display_original_state(self):
# Display the image in its original state
if self.image:
self.display_image(self.original_image)

def display_image(self, img):
# Display the given image on the canvas
self.image = img
self.image_tk = ImageTk.PhotoImage(self.image)
self.canvas.create_image(0, 0, anchor = tk.NW, image = self.image_tk)




if __name__ == "__main__":
root = tk.Tk()
app = PhotoEditorApp(root)
root.mainloop()



The Final Result:

Image Editor App In Python Tkinter

Edge Detection
Edge Detection

GrayScale
GrayScale

rotate (180 degree)
rotate (180 degree)

brightness enhancement
brightness enhancement

grayscale 2
grayscale

blur
blur

original image

invert colors
invert colors

edge detection
edge detection

crop image
crop image

mirror
mirror