简体   繁体   English

Kivy Buttons-单击播放声音

[英]Kivy Buttons- Play sound on click

I have looked at a few answers but I can't really make heads or tails of them. 我已经看了几个答案,但我无法真正做出决定。 When any of the buttons are pressed I want it to play "beep.wav". 当按下任何按钮时,我希望它播放“ beep.wav”。 Another problem I have is with the "return layout", where exactly should I be putting that in terms of indentation. 我遇到的另一个问题是“返回布局”,我应该将其确切地放在缩进位置。 Many thanks, Michael. 非常感谢,迈克尔。

import kivy
import random
from kivy.core.audio import SoundLoader
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout


def callback(instance):
        print('The button <%s> is being pressed' % instance.text)

red = [1,0,0,1]
green = [0,1,0,1]
blue =  [0,0,1,1]
purple = [1,0,1,1]

class Buttons(App):
    def Orientation(self, orient):
        self.orient = orient

    def build(self):
        layout = BoxLayout(padding=0, orientation=self.orient)
        colors = [red, green, blue, purple]

        for i in range(4):
            btn = Button(text="Test Button %s" % (i+1), background_color=random.choice(colors))
            layout.add_widget(btn)
            btn.bind(on_press=btn_pressed) 
        return layout

    def btn_pressed():
        sound = SoundLoader.load('beep.wav')
        sound.play()

if __name__ == "__main__":
    app = Buttons()
    app.Orientation(orient="vertical")
    app.run()

btn.bind(on_press=btn_pressed) btn.bind(on_press = BTN_PRESSED)

Make this btn.bind(on_press=self.btn_pressed) , it is not a local variable but can be accessed this way as a class method. 将此btn.bind(on_press=self.btn_pressed)设为非局部变量,但可以将其作为类方法进行访问。

Another problem I have is with the "return layout", where exactly should I be putting that in terms of indentation. 我遇到的另一个问题是“返回布局”,我应该将其确切地放在缩进位置。

The real question is where in the program logic should it be returned? 真正的问题是应在程序逻辑中将其返回什么位置? The answer is that the method should always return it because you always want it to be the root widget, so your current position (the final line of the method, which is always called) is fine. 答案是该方法应始终返回它,因为您始终希望它是根窗口小部件,因此您当前的位置(该方法的最后一行,总是被调用)是可以的。

I would create a .kv file 我将创建一个.kv文件

<Buttons>:
   Button1:
       background_color: 1,0,0,1
       text: "Play Sound"
       on_press: root.btn_pressed()
Button2: etc

That might isolate the problem. 那可能会隔离问题。 Then remove the return 然后删除退货

if_name__ == 'main':
    Button().run()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM