[英]How can I make a sound when a button is pressed?
Now I am going to design a little GUI game like find a pair.现在我要设计一个小游戏,比如找一对。 And I want to add the sound effect when I click every buttons on it.
我想在我点击每个按钮时添加音效。 But I don't know how to add these sound.
但我不知道如何添加这些声音。 As the previous answer How can I play a sound when a tkinter button is pushed?
如上一个答案按下 tkinter 按钮时如何播放声音? said, I need to defined the button as this way:
说,我需要这样定义按钮:
Button(root, text="Play music", command=play_music).pack()
The button has another feature.该按钮还有另一个功能。
Button(game_window,image=blank_image,command=cell_0).grid(row=1,column=1)
So how 'command=play_music'
should be placed?那么
'command=play_music'
应该如何放置呢?
make a change like this:做出这样的改变:
'Button(game_window,image=blank_image,command=lambda:[cell_0(),play()]).grid(row=1,column=1)' '按钮(game_window,image=blank_image,command=lambda:[cell_0(),play()]).grid(row=1,column=1)'
Then it works.然后它工作。
I think you want to alter your functions with a common functionality.我认为您想使用通用功能更改您的功能。 For this decorators are really good.
对于这个装饰器真的很好。 A decorator allows you to add functionality to existing functions.
装饰器允许您向现有功能添加功能。 An exampel can be found below:
可以在下面找到一个示例:
import tkinter as tk
import winsound as snd
def sound_decorator(function):
def wrapped_function(*args,**kwargs):
print('I am here')
snd.PlaySound('Sound.wav', snd.SND_FILENAME)
return function(*args,**kwargs)
return wrapped_function
@sound_decorator
def cmd():
print('command')
root = tk.Tk()
button = tk.Button(root, text = 'Play', command = cmd)
button.pack()
root.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.