简体   繁体   English

如何访问 py 文件中的 kivy 按钮 ID?

[英]How to access kivy button ids in py file?

I'm trying to work out which button has been selected and then if that button has been selected, assign it to a variable in my python file but I'm not sure how to access the button's id.我正在尝试确定选择了哪个按钮,然后如果选择了该按钮,请将其分配给我的 python 文件中的变量,但我不确定如何访问按钮的 ID。

The buttons below start off blue [0,0,1,0] and then when pressed, they turn green [0,1,0,1].下面的按钮从蓝色 [0,0,1,0] 开始,然后在按下时变为绿色 [0,1,0,1]。 My code below is successfully working out which buttons are green and then I've got a print function to show it's working.我下面的代码成功地确定了哪些按钮是绿色的,然后我打印了 function 以显示它正在工作。 It's here, where print(self.ids) is that I was to access each id (a through to f) of each of the buttons and store af in a variable.在这里, print(self.ids) 是我要访问每个按钮的每个 id(a 到 f)并将 af 存储在变量中的地方。

class WhatButton(Screen):
    back_color = ObjectProperty()

    def button_pressed(self):
        buttons = [self.ids.a.back_color, self.ids.b.back_color, self.ids.c.back_color,
                          self.ids.d.back_color, self.ids.e.back_color, self.ids.f.back_color]
        counter = 0
        for x in buttons:
            if x == [0, 1, 0, 1]:
                counter += 1
                print(self.ids)
            else:
                pass

        if counter == 0:
            self.none_selected()
        else:
            sm.current = "thank you"

Hopefully the above is clear, let me know if it needs any more explanation希望以上内容很清楚,如果需要更多解释,请告诉我

You could create six variable ('a' through 'f'), and set them all to 'no' initially.您可以创建六个变量(“a”到“f”),并最初将它们全部设置为“no”。 Then change the green ones to 'yes' in your button_pressed() method.然后在您的button_pressed()方法中将绿色的更改为“是”。

I believe a better way would be to create a dictionary of values with the 'a' through 'f' as the keys.我相信更好的方法是创建一个以“a”到“f”为键的值字典。 Here is a modified version of your code that does that:这是执行此操作的代码的修改版本:

def button_pressed(self):
    counter = 0
    self.selected = {}
    for x in ['a', 'b', 'c', 'd', 'e', 'f']:
        if self.ids[x].back_color == [0, 1, 0, 1]:
            counter += 1
            self.selected[x] = 'yes'
        else:
            self.selected[x] = 'no'
    print(self.selected)

    if counter == 0:
        self.none_selected()
    else:
        sm.current = "thank you"

Using this approach, you can access any of the values as self.selected['a'] (or any 'a' through 'f').使用这种方法,您可以访问self.selected['a']中的任何值(或任何 'a' 到 'f')。

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

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