【问题标题】:How can I make a sound when a button is pressed?按下按钮时如何发出声音?
【发布时间】:2022-01-10 09:20:05
【问题描述】:

现在我要设计一个小游戏,比如找一对。我想在我点击每个按钮时添加音效。但我不知道如何添加这些声音。如上一个答案 How can I play a sound when a tkinter button is pushed? 说,我需要这样定义按钮:

Button(root, text="Play music", command=play_music).pack()

该按钮还有另一个功能。

Button(game_window,image=blank_image,command=cell_0).grid(row=1,column=1)

那么'command=play_music'应该怎么放置呢?

【问题讨论】:

标签: python user-interface tkinter audio


【解决方案1】:

进行如下更改:

Button(game_window,image=blank_image,command=lambda:[cell_0(),play()]).grid(row=1,column=1)

然后就可以了。

【讨论】:

  • lambda 表达式只应在真正需要时使用,但它很难调试。出于同样的原因,我不建议在 lambda 表达式中使用多个函数。它可能会让你很难找出这里发生了什么,同时它不会引发错误。
【解决方案2】:

我想你想用一个通用的功能来改变你的功能。对于这个decorators 真的很好。装饰器允许您向现有功能添加功能。示例如下:

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

【讨论】:

    猜你喜欢
    • 2014-11-02
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多