- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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.
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.
- Related Articles
- 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 can I pass arguments to Tkinter button's callback command?
- How to play a custom ringtone/alarm sound in Android?
- Can I play the same sound more than once at the same time with HTML5?
- How to create a Tkinter toggle button?
- How do I change button size in Python Tkinter?
- How to play a custom sound on receiving notification in Android?
- How to play an android notification sound?
- How can I disable typing in a ttk.Combobox tkinter?
- How to create a Button on a Tkinter Canvas?
- How to play sound file in a web-page in the background?
- How to Disable / Enable a Button in TKinter?
- How to update a Button widget in Tkinter?
