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 mixture.load.music(filename).

  • Add mixture.music.play() to play the music.

Example

# 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
win.geometry("700x500")

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

label = Label(win, image=bg)
label.place(x=0, y=0)

# Initialize mixer module in pygame
pygame.mixer.init()

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

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

win.mainloop()

Output

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.

Updated on: 18-Jun-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements