7

I am building a program for Windows PCs that contains a lot of buttons and seems very plain. So I was wondering, can I make it so when you push a button (using tkinter), can I play a sound to liven up the program a bit? Please keep in mind I am learning so please dumb it down a bit.

martineau
  • 119,623
  • 25
  • 170
  • 301
Austin Hargis
  • 139
  • 1
  • 1
  • 12

4 Answers4

12

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()
Community
  • 1
  • 1
Malik Brahimi
  • 16,341
  • 7
  • 39
  • 70
  • does mp3play come in the default python library or do i have to dl it? – BOBTHEBUILDER Feb 06 '19 at 03:14
  • 1
    It does not work on my operation system, is the error was raised when I tried to run it in my Linux system – Roger Almengor Aug 25 '19 at 08:56
  • @RogerAlmengor of course, it is raised, because the **win**sound (and mp3play, too) are only for Windows, they're not cross-platform. To make my app work on more operation systems, I use Pygame. – Demian Wolf Apr 26 '20 at 12:45
5

You might want to consider using pygame as a cross-platform alternative to winsound.

import tkinter as tk

from pygame import mixer

mixer.init()
sound = mixer.Sound("sound.ogg")

root = tk.Tk()
tk.Button(root, command=sound.play).pack()
root.mainloop()

Refer to the docs for more information.

Demian Wolf
  • 1,698
  • 2
  • 14
  • 34
  • 1
    Right on. You don't have to import *all of pygame* for that tho. There's a good couple megs of graphical functions that'll never get touched. You could just import that required mixer component, `from pygame import mixer` then change all your commands from `pygame.mixer.init()` to simply read `mixer.init()` – Doyousketch2 Jul 02 '21 at 21:20
  • 1
    @Doyousketch2, thank you for the reply. Indeed, it's unnecessary to import all modules from `pygame` if all we need is `pygame.mixer`. Edited the answer. – Demian Wolf Jul 02 '21 at 23:14
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.

ca_san
  • 183
  • 2
  • 11
0

Just use

import os
os.system("play sound.mp3")