- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
# 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()
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.
- How can I identify when a Button is released in Tkinter?
- How do I make a pop-up in Tkinter when a button is clicked?
- Running multiple commands when a button is pressed in Tkinter
- How to play a custom ringtone/alarm sound in Android?
- How to play an android notification sound?
- How to play a custom sound on receiving notification in Android?
- Can I play the same sound more than once at the same time with HTML5?
- How to play sound using SoundPool in Kotlin?
- How to play sound file in a web-page in the background?
- How to play ringtone/alarm/notification sound in Android?
- How to play Beep sound through Console in C#?
- How can I pass arguments to Tkinter button's callback command?
- How do I get an event callback when a Tkinter Entry widget is modified?
- How can I disable typing in a ttk.Combobox tkinter?
- How to create a Tkinter toggle button?