victorcd
victorcd

Reputation: 439

Variable function as position

I am trying to associate the position of a button with the index of a list. I have one list containing many names, and another list containing many numeric values. I want to create a function that takes the position (or any other parameter) of its button, and associates its button position to a index of the list.

For example: when I click on the first button, the function takes the first name of the list, and takes the first numeric value of the other list. So I clicked the last button, and the function takes the last name of the list and the last numeric value the other list.

I did it creating many function as values, but I think that there is more intelligent way to do this.

.py

n = ["a", "b", "c", "d"]
v = [10, 20, 30, 40]
x = 0
y = []
i = 0
class PrimeiroScreen(Screen):
    def __init__(self, **kwargs):
        self.name = 'um'
        super(Screen,self).__init__(**kwargs)

    def fc1(self, *args):#I don't know how to make i variable as button position 
        global x
        x = x + v[i]
        y.append(n[i])
        print (x)
        print (y)

.kv

<PrimeiroScreen>:
    StackLayout:
        orientation: 'tb-lr'
        GridLayout:
            cols: 2
            spacing: 10, 10
            #padding: 0, 0
            size_hint: (1,.8)
            Button:
                text: "[b]Btn1[/b]"
                markup: True
                on_press: root.fc1()
            Button:
                text: "[b]Btn2[/b]"
                font_size: '20dp'
                markup: True
                on_press: root.fc1()
            Button:
                text: "[b]Btn3[/b]"
                font_size: '20dp'
                markup: True
                on_press: root.fc1()
            Button:
                text: "[b]Btn4[/b]"
                font_size: '20dp'
                markup: True
                on_press: root.fc1()

Upvotes: 0

Views: 64

Answers (1)

Yoav Glazner
Yoav Glazner

Reputation: 8066

In your case I would just send the button position to the fc1 function

....

    GridLayout:
        cols: 2
        spacing: 10, 10
        #padding: 0, 0
        size_hint: (1,.8)
        Button:
            text: "[b]Btn1[/b]"
            markup: True
            on_press: root.fc1(1) #woohoo!!!
        Button:
            text: "[b]Btn2[/b]"
            font_size: '20dp'
            markup: True
            on_press: root.fc1(2)
        Button:
            text: "[b]Btn3[/b]"
            font_size: '20dp'
            markup: True
            on_press: root.fc1(3)
        Button:
            text: "[b]Btn4[/b]"
            font_size: '20dp'
            markup: True
            on_press: root.fc1(4) 

and now you have:

 def fc1(self, i):
    global x

    x = x + v[i]
    y.append(n[i])
    print (x)
    print (y)

Upvotes: 1

Related Questions