简体   繁体   English

按下按钮时如何发出声音?

[英]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.

相关问题 当在 OptionMenu 上选择一个选项并按下一个按钮然后为该特定选项发生某些事情时,我该如何做到这一点 - How can I make it so when an Option is chosen on OptionMenu and a button is pressed then for something to happen for that specific option 按下按钮后,如何使HTML按钮影响python脚本的数据? - How can I make an HTML button affect the data of a python script when pressed? python) 当按下按钮时,如何使 tkinter 出现? - python) How do I make tkinter appear when a button is pressed? 如何在.kv文件上绑定按钮以使其播放声音? - How can I bind a button on the .kv file to make it play a sound? 按下tkinter上的一个按钮时,如何中断睡眠 - How can I break the sleep when I pressed a button on tkinter 如何在Kivy中有一个按钮,当按下按钮时会创建标签? - How can I have a button in Kivy that when pressed, creates a label? 我怎样才能做到 Tkinter 按钮只能按一次? - How can I make it so the Tkinter button can only be pressed once? 按下后如何禁用按钮? - How can I disable a button after pressed? 按下按钮时,如何使按钮的名称传递给函数? - How do I make a button pass its name to a function, when it is pressed? 按下鼠标按钮后,如何使程序不会无限循环运行 - How can I make my program not run in an endless loop once my mouse button is pressed
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM