How can I play a sound when a tkinter button is pu

2019-03-03 16:21发布

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.

2条回答
女痞
2楼-- · 2019-03-03 17:00

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.

查看更多
Lonely孤独者°
3楼-- · 2019-03-03 17:06

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()
查看更多
登录 后发表回答