在 Tkinter 按钮被按下时如何播放声音?


Python 有许多用于构建各种应用程序界面和组件的内置库和模块。Pygame 是用于设计和构建视频游戏和音乐的 python 模块之一。它提供了混合所有声音相关活动的混合。使用music 子模块,你可以流式传输 mp3、ogg 和其他各种声音。

要创建一个在点击按钮时播放声音的应用程序,我们必须遵循以下步骤,

  • 确保Pygame 已安装在你的本地计算机中。你可以使用pip install pygame 命令安装pygame

  • 使用pygame.mixture.init() 初始化Pygame 混合。

  • 创建一个按钮小组件,在播放音乐时使用它。

  • 定义一个函数play_sound() ,并通过指定mixture.load.music(filename) 中的文件位置加载音乐。

  • 添加mixture.music.play() 播放音乐。

示例

# 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()

输出

如果我们运行以上代码,它会显示一个带有一个按钮的窗口。现在,在给定的函数中添加音乐位置以在应用程序中播放音乐。

更新日期:18-06-2021

3K+ 查看次数

开启您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.