How can I play a sound when a Tkinter button is pushed?


Python has many inbuilt libraries and modules that are used for building various application interfaces and components. Pygame is one of the python modules which is used to design and build video games and music. It provides a mixture to handle all sound related activities. Using music sub-module, you can stream mp3, ogg, and other variety of sounds.

To create an application that plays some sound on clicking a button, we have to follow these steps,

  • Make sure that Pygame is installed in your local machine. You can install pygame using pip install pygame command.

  • Initialize Pygame mixture by using pygame.mixture.init()

  • Create a button widget which is used further to play the music.

  • Define a function play_sound() and load the music by specifying the location of the file in

  • Add to play the music.


# Import the required libraries
from tkinter import *
import pygame
from PIL import Image, ImageTk

# Create an instance of tkinter frame or window
win = Tk()

# Set the size of the window

# Add a background image
bg = ImageTk.PhotoImage(file="music.jpg")

label = Label(win, image=bg), y=0)

# Initialize mixer module in pygame

# Define a function to play the music
def play_sound():"sample1.mp3")

# Add a Button widget
b1 = Button(win, text="Play Music", command=play_sound)



If we run the above code, it will display a window with a button in it. Now, add music location in the given function to play some music in the application.

Published on 18-Jun-2021 13:48:18