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

Solution 1:

Assuming your file is a WAV:

from tkinter import *
from winsound import *

root = Tk() # create tkinter window

play = lambda: PlaySound('Sound.wav', SND_FILENAME)
button = Button(root, text = 'Play', command = play)

button.pack()
root.mainloop()

Assuming your file is a MP3:

from Tkinter import *
import mp3play

root = Tk() # create tkinter window

f = mp3play.load('Sound.mp3'); play = lambda: f.play()
button = Button(root, text = 'Play', command = play)

button.pack()
root.mainloop()

Solution 2:

You can also use pygame. Despite being slightly slower than some libraries for playing music only, it is cross-platform.

Here is an example of using it in a Tkinter-based app:

import tkinter as tk
from pygame import mixer


mixer.init()

def play_music():
    mixer.music.load("sample.ogg")
    mixer.music.play()
    
root = tk.Tk()
tk.Button(root, text="Play music", command=play_music).pack()
root.mainloop()

It is important to keep in mind which sound formats are supported. From the docs:

  1. pygame.mixer docs:

The Sound can be loaded from an OGG audio file or from an uncompressed WAV.

  1. pygame.music docs:

Be aware that MP3 support is limited. On some systems an unsupported format can crash the program, e.g. Debian Linux. Consider using OGG instead.

Solution 3:

You first need to link the click of your mouse on the image, with an even handler, then simply define an on_click function:

def on_click(event): 
    winsound.Beep('frequency', 'duration')

Here you can find more information about playing sounds in python.