Dùng thư viện pygame để phát âm thanh khi nhấn Button Tkinter.
- Cài đặt:
pip install pygame. - Khởi tạo mixer:
pygame.mixer.init(). - Hàm
play_sound()load file nhạc và phát bằngpygame.mixer.music.play().
Ví dụ minh họa
from tkinter import *
import pygame
from PIL import Image, ImageTk
win = Tk()
win.geometry("700x500")
bg = ImageTk.PhotoImage(file="music.jpg")
Label(win, image=bg).place(x=0, y=0)
pygame.mixer.init()
def play_sound():
pygame.mixer.music.load("sample1.mp3")
pygame.mixer.music.play()
Button(win, text="Phát nhạc", command=play_sound).pack(pady=60)
win.mainloop()
Kết quả đầu ra
Cửa sổ có nút Phát nhạc, nhấn để nghe file sample1.mp3.
