0

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? 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?

Thingamabobs
  • 7,274
  • 5
  • 21
  • 54

2 Answers2

0

make a change like this:

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

Then it works.

Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
  • lambda expressions should only used if really needed, while its hard to debug. For the same reason I wouldnt recommand to use multiple functions in a lambda expression. It could give you a hard time to find out what happens here, while it dosent throws an error. – Thingamabobs Dec 04 '21 at 08:23
0

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()
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54