【问题标题】:Kivy/python. One callback function for several buttons基维/蟒蛇。多个按钮的一个回调函数
【发布时间】:2016-03-17 18:51:47
【问题描述】:

我开始实现一个带有树莓派和触摸屏的网络收音机。我在屏幕上放置了几个按钮,我想为所有按钮实现一个回调函数。通过 if-else 结构区分按下哪个按钮。

kv 文件:

BoxLayout:
    Button:
        text: "PLAY"
        on_press: root.ctrl_buttons()
    Button:
        text: "STOP"
        on_press: root.ctrl_buttons()

python 文件:

def ctrl_buttons(self):
    if "play pressed":
        subprocess.check_output("mpc play", shell=True)
     elif "stop pressed":
         subprocess.check_output("mpc stop", shell=True)

我没有找到用参数调用回调函数的方法,我可以在 if-else 结构中有所不同。

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    为什么不在函数中使用另一个参数?

    def ctrl_buttons(self, button):
        if button=="PLAY":
            print "pressed play"
        elif button=="STOP":
            print "pressed stop"
    

    在 kivy 中使用 root.ctrl_buttons(self.text)

    不记得它是否需要另一个参数或不仅仅是传递按钮,但如果是,那么这更有效:

    def ctrl_buttons(self, button):
        if button.text=="PLAY":
            print "pressed play"
        elif button.text=="STOP":
            print "pressed stop"
    

    【讨论】:

    • 我尝试了很多不同的想法,但没有任何效果。我认为它总是对正确的代码有所帮助。谢谢。
    • 我知道这种感觉。就像你知道你快到了一样,只需要一点点改变。
    猜你喜欢
    • 1970-01-01
    • 2014-02-14
    • 2013-03-05
    • 2012-03-25
    • 2021-08-10
    • 1970-01-01
    • 2022-06-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多