Java - Button With Background Image

How to Create a Button with specified text and background image In Java Netbeans



In this Java Tutorial we will see How To Create a Buttons with background image In Java Using Netbeans.


What We're Building
Our custom button includes:
    - Background Images: Any image as button background with automatic scaling.
    - Hover Animations: Shadow effects that animate on mouse interaction.
    - Press Effects: Visual feedback when buttons are clicked.
    - Rounded Corners: Modern button appearance with customizable corner radius

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.





Project Source Code:





public class ButtonWithImage extends  JFrame{

    public ButtonWithImage(){
        
        setTitle("Button Image");
        setSize(600, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        
        JPanel mainPanel = new JPanel(new GridBagLayout());
        mainPanel.setBackground(Color.WHITE);
        
        String imagePath = ButtonWithImage.class.getResource("pic_sport.jpg").getPath();
        ButtonImage button = new ButtonImage("Click", imagePath);
        button.setPreferredSize(new Dimension(250, 100));
        
        String imagePath2 = ButtonWithImage.class.getResource("pic_taxi.png").getPath();
        ButtonImage button2 = new ButtonImage("Click", imagePath2);
        button2.setPreferredSize(new Dimension(250, 100));
        
        button.addActionListener(e -> {
            JOptionPane.showMessageDialog(this, "Button 1 Clicked!",
                    "Action", JOptionPane.PLAIN_MESSAGE);
        });
        
         button2.addActionListener(e -> {
            JOptionPane.showMessageDialog(this, "Button 2 Clicked!",
                    "Action", JOptionPane.PLAIN_MESSAGE);
        });
        
        
        mainPanel.add(button);
        mainPanel.add(button2);
        
        
        setContentPane(mainPanel);
        
    }
    
    public static void main(String[] args) {
        
        new ButtonWithImage().setVisible(true);
        
    }
    
}

/**
 * Custom button implementation with modern visual effects
 */
class ButtonImage extends JButton{
    
    private BufferedImage backgroundImage;
    private boolean isHovered = false;
    private boolean isPressed = false;
    private float shadowOpacity = 0.0f;
    private Timer shadowTimer;
    
    private static final int CORNER_RADIUS = 12;
    private static final int SHADOW_SIZE = 20;
    private static final float SHADOW_MAX_OPACITY = 0.3f;
    
    public ButtonImage(String text, String imagePath){
        
        super(text);
        initializeButton();
        loadBackgroundImage(imagePath);
        setupAnimation();
        
    }
    
    
    private void initializeButton(){
         // Turn off the default button background
        setContentAreaFilled(false);
        // Turn off the focus border
        setFocusPainted(false);
        // Turn off the default button border
        setBorderPainted(false);
        // Set the text color to white
        setForeground(Color.WHITE);
        // Set the text font
        setFont(new Font("Arial", Font.BOLD, 26));
        // Change the mouse cursor to a hand when hovering over the button
        setCursor(new Cursor(Cursor.HAND_CURSOR));
        
         // Add code to detect mouse interactions
         addMouseListener(new MouseAdapter() {
             
             @Override
             public void mouseEntered(MouseEvent e){
                 // Mouse has moved onto the button
                 isHovered = true;
                 // Start the shadow animation
                 shadowTimer.start();
                 // Redraw the button with the new state
                 repaint();
             }
             
             @Override
             public void mouseExited(MouseEvent e){
                 // Mouse has moved away from the button
                 isHovered = false;
                 isPressed = false;
                 // Start the shadow animation
                 shadowTimer.start();
                 // Redraw the button with the new state
                 repaint();
             }
             
             @Override
             public void mousePressed(MouseEvent e){
                // Button is being pressed down
                isPressed = true;
                // Redraw the button with the new state
                repaint();
             }
             
             @Override
             public void mouseReleased(MouseEvent e){
                // Button is being pressed down
                isPressed = false;
                // Redraw the button with the new state
                repaint();
             }
             
         });
        
    }
    
    private void loadBackgroundImage(String imagePath){
        
        try {
            backgroundImage = ImageIO.read(new File(imagePath));
        } catch (IOException ex) {
            backgroundImage = createGradientBackground(250, 100);
        }
        
    }
    
    
    private BufferedImage createGradientBackground( int width, int height ){
        BufferedImage gradientImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        
        Graphics2D g2d = gradientImage.createGraphics();
        
        GradientPaint  gradientPaint =  new GradientPaint(0, 0, Color.BLACK,
                                                                         width, height, Color.BLUE);
        
        g2d.setPaint(gradientPaint);
        g2d.fillRect(0, 0, width, height);
        g2d.dispose();
        
        return gradientImage;
    }
    
    
    private void setupAnimation(){
        // Create a timer that fires every 15 milliseconds
        shadowTimer = new Timer(15, e ->{
            // Determine target opacity based on hover state
            float targetOpacity = isHovered ? SHADOW_MAX_OPACITY : 0.0f;
            // Gradually change the current opacity toward the target
            shadowOpacity += (targetOpacity - shadowOpacity) * 0.2f;
            // If we're very close to the target, just set it exactly and stop the timer
            if(Math.abs(targetOpacity - shadowOpacity) < 0.01f){
                shadowOpacity = targetOpacity;
                ((Timer) e.getSource()).stop();
            }
            
            // Redraw the button with the new shadow opacity
            repaint();
        
        });
    }
    
    
    @Override
    protected void paintComponent(Graphics g){
        // Create a copy of the graphics object that we can modify
        Graphics2D g2d = (Graphics2D)g.create();
        
        // Set up graphics quality settings
        configureGraphics(g2d);
        
        // Create the rounded rectangle shape for our button
        RoundRectangle2D.Float buttonShape = new RoundRectangle2D.Float(
                SHADOW_SIZE / 2,  SHADOW_SIZE / 2, getWidth() -  SHADOW_SIZE, getHeight() -  SHADOW_SIZE,
                CORNER_RADIUS, CORNER_RADIUS
        );
        
        // Draw the shadow if it should be visible
        if(shadowOpacity > 0){ drawShadow(g2d, buttonShape);  }
        
        // Only draw inside the button shape
        g2d.setClip(buttonShape);
        
        // Draw the background image
        drawBackground(g2d);
        
        // Draw the button text
        drawText(g2d);
        
        // Draw hover and press effects
        drawOverlayEffects(g2d, buttonShape);
        
        g2d.dispose();
        
    }
    
    private void drawBackground(Graphics2D g2d){
        // If we have a background image, draw it stretched to the button size
        if(backgroundImage != null){
            g2d.drawImage(backgroundImage, 0, 0, getWidth(), getHeight(), null);
        }
    }
    
    
    private void configureGraphics(Graphics2D g2d){
        // Turn on anti-aliasing for smoother edges
        g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        // Turn on high quality text rendering
        g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        // Use better image scaling
        g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        
    }
    
    
   private void drawShadow(Graphics2D g2d, RoundRectangle2D.Float buttonShape){
        // Draw multiple lines with decreasing thickness to create a shadow effect
       for(int i = SHADOW_SIZE; i > 0; i--){
           // Calculate alpha based on distance from button and overall shadow opacity
           float alpha = shadowOpacity * (1.0f - (float) i / SHADOW_SIZE);
           // Set the shadow color (black with varying transparency)
           g2d.setColor(new Color(0,0,0, (int)(alpha * 60)));
           // Set the line thickness
           g2d.setStroke(new BasicStroke(i));
           // Draw the outline of the button
           g2d.draw(buttonShape);
           
       }
       
    }
    
    
  private void drawOverlayEffects(Graphics2D g2d, Shape buttonShape){

        if(isPressed){
            g2d.setColor(new Color(0, 0, 0, 40));
            g2d.fill(buttonShape);
        }
        else if(isHovered){
            g2d.setColor(new Color(255, 255, 255, 30));
            g2d.fill(buttonShape);
        }
      
    }
    
    
   private void drawText(Graphics2D g2d){
       
        // Get information about the size of the text
        FontMetrics metrics = g2d.getFontMetrics(getFont());
        String text = getText();
         // Calculate position to center the text horizontally
        int x = (getWidth() - metrics.stringWidth(text)) / 2;
        // Calculate position to center the text vertically
        int y = ((getHeight() - metrics.getHeight()) / 2 ) + metrics.getAscent();
        // Set the text color
        g2d.setColor(getForeground());
        // Draw the text on the button
       g2d.drawString(getText(), x, y);
       

    }
    
}
  


The Final Result:















Python Tkinter Hamburger Menu

How To Create a Hamburger Menu Dashboard In Python Tkinter



In this Python Tutorial we will see How to Create a dashboard with a smooth sliding hamburger menu using Python  and Tkinter library.

What We Are Gonna Use In This Project:

- Python Programming Language.
- Tkinter (GUI).
- VS Editor.






Project Source Code:




import math
import tkinter as tk
from tkinter import ttk
import time

class HamburgerMenu:
def __init__(self, master):
"""Initialize the Dashboard application
Args:
master: The tkinter root window
"""
self.master = master
self.master.title("Dashboard")
# Configure the main window size and background color
self.master.geometry("1000x700")
self.master.configure(bg='#1a1a1a') # Dark background for modern look
# Initialize menu state variables
self.menu_expanded = False # Track if side menu is expanded
self.menu_width = 0 # Current width of the menu (for animation)
self.target_width = 280 # Target width when menu is fully expanded
self.animation_speed = 15 # Controls how fast the menu slides
self.animation_running = False # Flag to prevent multiple animations
self.active_menu = "Home" # Track which menu item is currently active
# Build the UI components
self.setup_frames()
self.create_title()
self.create_hamburger_button()
self.create_menu_items()
self.create_content()

def setup_frames(self):
"""Create and configure the main frame structure of the application"""
# Create the header bar at the top
self.header_frame = tk.Frame(self.master, bg='#121212', height=70)
self.header_frame.pack(fill='x', side='top')
self.header_frame.pack_propagate(False) # Prevent the frame from shrinking
# Add a thin separator line below the header
self.separator_frame = tk.Frame(self.master, height=2, bg='#2a2a2a')
self.separator_frame.pack(fill='x')
# Main container that will hold both menu and content
self.container = tk.Frame(self.master, bg='#121212')
self.container.pack(fill='both', expand=True)
# This is the sliding menu panel container (starts with zero width)
self.menu_container = tk.Frame(self.container, bg='#121212', width=0)
self.menu_container.pack(side='left', fill='y')
# Important to maintain controlled width
self.menu_container.pack_propagate(False)
# Inner menu frame with padding for a polished look
self.menu_frame = tk.Frame(self.menu_container, bg='#1e1e1e', bd=0)
self.menu_frame.pack(fill='both', expand=True, padx=(10, 5), pady=10)
# Main content area where dashboards will be displayed
self.content_frame = tk.Frame(self.container, bg='#121212')
self.content_frame.pack(side='left', fill='both', expand=True,
padx=20, pady=10)

def create_title(self):
"""Create the title/logo area in the header"""
# Frame to hold the title elements
title_frame = tk.Frame(self.header_frame, bg='#121212')
title_frame.pack(side='left', padx=(70, 0))
# Create a small colored vertical bar as a design accent
accent = tk.Frame(title_frame, width=4, height=24, bg='#4a9eff')
accent.pack(side='left', padx=(0, 10))
# The actual title text
title_label = tk.Label(
title_frame,
text="DASHBOARD",
font=("Helvetica", 16, "bold"),
bg='#121212',
fg='#ffffff'
)
title_label.pack(side='left')
# Add current time display to header
self.time_label = tk.Label(
self.header_frame,
text="",
font=("Helvetica", 12),
bg='#121212',
fg='#888888'
)
self.time_label.pack(side='right', padx=20)
self.update_time() # Start the time update loop

def update_time(self):
"""Update the time display in the header (called every second)"""
current_time = time.strftime("%H:%M:%S")
self.time_label.config(text=current_time)
self.master.after(1000, self.update_time) # Schedule the next update


def create_hamburger_button(self):
"""Create the hamburger menu button with hover effects"""
# Use a canvas to create a circular button
self.button_canvas = tk.Canvas(
self.header_frame,
width=40,
height=40,
bg='#121212',
highlightthickness=0 # Remove the default canvas border
)
self.button_canvas.place(x=15, y=15)
# Draw the circular background
self.button_bg = self.button_canvas.create_oval(0, 0, 40, 40,
fill='#1e1e1e', outline='')
# Add the hamburger icon (☰) text
self.button_text = self.button_canvas.create_text(
20, 20, # Center of the circle
text="☰",
font=("Helvetica", 18),
fill='#ffffff'
)
# Bind mouse events for interactivity
self.button_canvas.bind('<Button-1>', self.toggle_menu) # Click event
self.button_canvas.bind('<Enter>', self.hamburger_hover_in) # Mouse enter
self.button_canvas.bind('<Leave>', self.hamburger_hover_out) # Mouse leave
self.button_canvas.configure(cursor="hand2") # Change cursor to hand on hover

def hamburger_hover_in(self, event):
"""Handle mouse enter event on hamburger button"""
# Darken background
self.button_canvas.itemconfig(self.button_bg, fill='#252525')
# Change icon color
self.button_canvas.itemconfig(self.button_text, fill='#4a9eff')

def hamburger_hover_out(self, event):
"""Handle mouse leave event on hamburger button"""
# Restore background
self.button_canvas.itemconfig(self.button_bg, fill='#1e1e1e')
# Restore icon color
self.button_canvas.itemconfig(self.button_text, fill='#ffffff')

def create_menu_items(self):
"""Create the sliding menu with all menu items"""
# Define menu items with their icons, labels and accent colors
menu_items = [
("⌂", "Home", "#4a9eff"),
("◉", "Profile", "#4ecdc4"),
("⚙", "Settings", "#9b59b6"),
("△", "Analytics", "#3498db"),
("✉", "Messages", "#e74c3c"),
("?", "Support", "#f1c40f"),
]
# Create profile section at the top of menu
self.create_profile_section()
# Create menu header with "MENU" text
menu_header = tk.Frame(self.menu_frame, bg='#1e1e1e', height=30)
menu_header.pack(fill='x', pady=(20, 15))
menu_header.pack_propagate(False)
tk.Label(
menu_header,
text="MENU",
font=("Helvetica", 10, "bold"),
bg='#1e1e1e',
fg='#555555'
).pack(side='left', padx=15, pady=10)
# Container frame for all menu items with some padding
menu_items_container = tk.Frame(self.menu_frame, bg='#1e1e1e')
menu_items_container.pack(fill='x', padx=5)

# Store references to all menu buttons for later access
self.menu_buttons = []
# Create each menu item
for icon, text, color in menu_items:
# Create a frame for each menu item
item_frame = tk.Frame(menu_items_container, bg='#1e1e1e', height=50)
item_frame.pack(fill='x', pady=3)
item_frame.pack_propagate(False)
# Use canvas for better visual control
item_canvas = tk.Canvas(
item_frame,
bg='#1e1e1e',
highlightthickness=0,
height=50
)
item_canvas.pack(fill='x')
# Store references for the canvas and its rectangle for hover effects
item_frame.canvas = item_canvas
item_frame.bg_rect = item_canvas.create_rectangle(
0, 0, 280, 50,
fill='#1e1e1e',
outline='',
width=0
)
# Create left accent bar with the item's color
accent_rect = item_canvas.create_rectangle(
8, 10, 12, 40,
fill=color,
outline='',
width=0
)
# Hide accent initially (only shown on hover/active)
item_canvas.itemconfig(accent_rect, state='hidden')
item_frame.accent_rect = accent_rect
# Add icon with subtle background in a circular shape
icon_x, icon_y = 30, 25
# Draw circular background for icon
icon_bg = item_canvas.create_oval(
icon_x-15, icon_y-15,
icon_x+15, icon_y+15,
fill='#252525',
outline=''
)
# Draw the icon text
icon_text = item_canvas.create_text(
icon_x, icon_y,
text=icon,
font=("Helvetica", 14),
fill='#ffffff'
)
# Add menu text
text_label = item_canvas.create_text(
80, 25,
text=text,
font=("Helvetica", 12),
fill='#ffffff',
anchor='w'
)
# Check if this is the active menu and style it accordingly
if text == self.active_menu:
# Highlight the active menu
item_canvas.itemconfig(item_frame.bg_rect, fill='#252525')
item_canvas.itemconfig(accent_rect, state='normal')
# Store the active state
item_frame.active = True
else:
item_frame.active = False
# Store color references for hover effects
item_frame.original_bg = '#1e1e1e' # Default background
item_frame.hover_bg = '#252525' # Background on hover
item_frame.active_bg = '#2a2a2a' # Background when active
item_frame.accent_color = color # Accent color for this item
item_frame.text = text # Menu item text for reference
# Bind hover and click events
item_canvas.bind('<Enter>', lambda e,
f=item_frame: self.menu_item_hover_in(f))
item_canvas.bind('<Leave>', lambda e,
f=item_frame: self.menu_item_hover_out(f))
item_canvas.bind('<Button-1>', lambda e,
f=item_frame: self.menu_item_click(f))
# Change cursor on hover
item_canvas.configure(cursor="hand2")
# Add to list of menu buttons for later reference
self.menu_buttons.append(item_frame)

# Add a divider below menu items
divider = tk.Frame(self.menu_frame, height=1, bg='#2a2a2a')
divider.pack(fill='x', pady=15, padx=15)
# Add logout button at the bottom
self.create_logout_button()


def create_profile_section(self):
"""Create the user profile section at the top of the menu"""
# Profile section container
profile_frame = tk.Frame(self.menu_frame, bg='#1e1e1e', height=90)
profile_frame.pack(fill='x', pady=(15, 0))
profile_frame.pack_propagate(False)
# Create a canvas for the profile circle
profile_canvas = tk.Canvas(
profile_frame,
width=70,
height=70,
bg='#1e1e1e',
highlightthickness=0
)
profile_canvas.place(relx=0.5, y=10, anchor='n') # Center horizontally
# Draw circular profile background
profile_bg = profile_canvas.create_oval(5, 5, 65, 65,
fill='#252525', outline='')
# Draw profile placeholder with user initials
profile_text = profile_canvas.create_text(
35, 35, # Center of the circle
text="JD", # User initials (John Doe)
font=("Helvetica", 22, "bold"),
fill='#4a9eff'
)
# Add user name below profile image
tk.Label(
profile_frame,
text="John Doe",
font=("Helvetica", 12, "bold"),
bg='#1e1e1e',
fg='#ffffff'
).place(relx=0.5, y=90, anchor='s') # Center horizontally

def create_logout_button(self):
"""Create the logout button at the bottom of the menu"""
# Create a frame for logout button
logout_frame = tk.Frame(self.menu_frame, bg='#1e1e1e', height=50)
logout_frame.pack(fill='x', side='bottom', padx=15, pady=10)
# Create a canvas for the logout button to add rounded corners effect
logout_canvas = tk.Canvas(
logout_frame,
bg='#1e1e1e',
highlightthickness=0,
height=45
)
logout_canvas.pack(fill='x')
# Draw rectangle background
logout_bg = logout_canvas.create_rectangle(
0, 0, 280, 45,
fill='#252525',
outline='',
width=0
)
# Add icon and text
logout_icon = logout_canvas.create_text(
25, 23,
text="→", # Right arrow icon
font=("Helvetica", 14),
fill='#e74c3c',
anchor='w'
)
logout_text = logout_canvas.create_text(
55, 23,
text="Logout",
font=("Helvetica", 12, "bold"),
fill='#ffffff',
anchor='w'
)
# Add hover effects
def on_enter(e):
"""Mouse enter effect for logout button"""
logout_canvas.itemconfig(logout_bg, fill='#2c2c2c')
logout_canvas.itemconfig(logout_text, fill='#e74c3c')
def on_leave(e):
"""Mouse leave effect for logout button"""
logout_canvas.itemconfig(logout_bg, fill='#252525')
logout_canvas.itemconfig(logout_text, fill='#ffffff')
# Bind events
logout_canvas.bind('<Enter>', on_enter)
logout_canvas.bind('<Leave>', on_leave)
logout_canvas.bind('<Button-1>', lambda e: print("Logout clicked"))
logout_canvas.configure(cursor="hand2")
def menu_item_hover_in(self, frame):
"""Handle mouse enter event on menu items
Args:
frame: The menu item frame being hovered
"""
# Only change appearance if this isn't the active menu item
if not frame.active:
frame.canvas.itemconfig(frame.bg_rect, fill=frame.hover_bg)
frame.canvas.itemconfig(frame.accent_rect, state='normal')
def menu_item_hover_out(self, frame):
"""Handle mouse leave event on menu items
Args:
frame: The menu item frame being left
"""
# Only change appearance if this isn't the active menu item
if not frame.active:
frame.canvas.itemconfig(frame.bg_rect, fill=frame.original_bg)
frame.canvas.itemconfig(frame.accent_rect, state='hidden')

def menu_item_click(self, frame):
"""Handle click event on menu items
Args:
frame: The menu item frame being clicked
"""
# Deactivate all menu items first
for btn in self.menu_buttons:
btn.active = False
btn.canvas.itemconfig(btn.bg_rect, fill=btn.original_bg)
btn.canvas.itemconfig(btn.accent_rect, state='hidden')
# Activate the clicked item
frame.active = True
frame.canvas.itemconfig(frame.bg_rect, fill=frame.active_bg)
frame.canvas.itemconfig(frame.accent_rect, state='normal')
# Update the active menu
self.active_menu = frame.text
print(f"Clicked on {frame.text}")




def create_content(self):
"""Create the main content area with welcome panel and info cards"""
# Create welcome panel at the top
self.welcome_frame = tk.Frame(self.content_frame, bg='#181818', height=200)
self.welcome_frame.pack(fill='x', pady=(0, 20))
self.welcome_frame.pack_propagate(False)
# Add decorative accent line
accent_line = tk.Frame(self.welcome_frame, bg='#4a9eff', width=80, height=3)
accent_line.place(x=40, y=40)
# Welcome text
tk.Label(
self.welcome_frame,
text="Welcome Back!",
font=("Helvetica", 28, "bold"),
bg='#181818',
fg='#ffffff'
).place(x=40, y=55)
tk.Label(
self.welcome_frame,
text="Explore your dashboard and manage your content",
font=("Helvetica", 12),
bg='#181818',
fg='#888888'
).place(x=40, y=100)
# Create a status indicator with green dot
status_frame = tk.Frame(self.welcome_frame, bg='#181818')
status_frame.place(x=40, y=140)
status_dot = tk.Canvas(status_frame, width=12, height=12,
bg='#181818', highlightthickness=0)
status_dot.pack(side='left')
status_dot.create_oval(0, 0, 10, 10, fill='#2ecc71', outline='') # Green dot
tk.Label(
status_frame,
text="All systems operational",
font=("Helvetica", 11),
bg='#181818',
fg='#2ecc71'
).pack(side='left', padx=5)
# Create three info cards section
self.card_container = tk.Frame(self.content_frame, bg='#121212')
self.card_container.pack(fill='x')
# Define data for the three cards
cards_data = [
("Statistics", "#2980b9", "128", "Active Users"),
("Performance", "#27ae60", "94%", "System Uptime"),
("Activity", "#8e44ad", "37", "New Events")
]
# Store card widgets for animation
self.content_cards = []
# Create each info card
for title, color, number, subtitle in cards_data:
card = tk.Frame(self.card_container, bg='#181818', width=200, height=150)
card.pack(side='left', padx=10, fill='both', expand=True)
card.pack_propagate(False)
# Add colored top border as accent
top_border = tk.Frame(card, height=3, bg=color)
top_border.pack(fill='x', side='top')
# Add card content - title, number, and subtitle
tk.Label(
card,
text=title,
font=("Helvetica", 14, "bold"),
bg='#181818',
fg='#ffffff'
).pack(anchor='w', padx=15, pady=(20, 5))
tk.Label(
card,
text=number,
font=("Helvetica", 28, "bold"),
bg='#181818',
fg=color
).pack(anchor='w', padx=15, pady=(5, 0))
tk.Label(
card,
text=subtitle,
font=("Helvetica", 12),
bg='#181818',
fg='#888888'
).pack(anchor='w', padx=15, pady=(0, 15))
# Add card to list for animation
self.content_cards.append(card)




def toggle_menu(self, event=None):
"""Toggle the side menu open/closed when hamburger button is clicked"""
# Prevent multiple animations from running at once
if self.animation_running:
return
# Toggle the menu state
if not self.menu_expanded:
self.expand_menu()
else:
self.collapse_menu()
# Change hamburger button to X or back
if self.menu_expanded:
self.button_canvas.itemconfig(self.button_text, text="✕") # X icon
else:
self.button_canvas.itemconfig(self.button_text, text="☰") # Hamburger icon


def expand_menu(self):
"""Start animation to expand the side menu"""
self.menu_expanded = True
self.animation_running = True
self.animate_menu()


def collapse_menu(self):
"""Start animation to collapse the side menu"""
self.menu_expanded = False
self.animation_running = True
self.animate_menu()



def animate_menu(self):
"""Handle the smooth animation of the side menu sliding in/out"""
# Target width is either full width or zero
# depending on if expanding/collapsing
target = self.target_width if self.menu_expanded else 0
def update():
"""Update function called repeatedly during animation"""
current_width = self.menu_container.winfo_width()
# Calculate the step size for smooth easing effect
if self.menu_expanded:
# When expanding, move faster when further from target
distance = target - current_width
step = max(1, int(distance * 0.2)) # At least 1 pixel
new_width = min(current_width + step, target)
else:
# When collapsing, move faster when further from zero
distance = current_width
step = max(1, int(distance * 0.2)) # At least 1 pixel
new_width = max(current_width - step, target)
# Update the menu width
self.menu_container.configure(width=new_width)
# Continue animation if not reached target
if new_width != target:
self.master.after(8, update) # Schedule next update
else:
self.animation_running = False # Animation complete

# Start the animation
update()




def main():
"""Main entry point of the application"""
root = tk.Tk()
app = HamburgerMenu(root)
root.mainloop()

if __name__ == "__main__":
main()



The Final Result: