KIVY python:在python代码中点击按钮

时间:2017-10-27 14:46:19

标签: button kivy

我有一个ScrollView,其中有一个GridLayout,其中有10个按钮。 我无法解决我的问题:只使用python文件(没有.kv)将所有按钮添加到网格布局中,所以我需要添加一个" on_press:"当我创建每个按钮。 我希望每个按钮在点击时打印其名称('文字:某些'属性)。

debug.kv

#: kivy 1.9.1

<AppScreenManager>:
    Home:

Home:

debug.py

from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.core.window import Window
from kivy.uix.button import Button
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.lang import Builder

class AppScreenManager(ScreenManager):
    def __init__(self, **kwargs):
        super(AppScreenManager, self).__init__(**kwargs)

class Home(Screen):

    def __init__(self, **kwargs):
        super(Home, self).__init__(**kwargs)
        self.myinit()

    # function that loads 10 buttons on the Home menu (in a ScrollView) when it is launched
    def myinit(self):

        # create some strings
        numbers = [str(i) for i in range(1, 11)]

        # The scrollview will contain this grid layout
        self.layout = GridLayout(cols=1, padding=5, spacing=5, size_hint=(1,None))
        # I don't know why do this line exists but it works x)
        self.layout.bind(minimum_height=self.layout.setter('height'))

        # create 10 buttons
        for number in numbers:
            ### My problem is HERE, under this line, with the on_press property ###
            btn = Button(text=number, on_press=print number, background_color=(.7, .7, .7, 1), color=(1,1,1,1), size=(32,32), size_hint=(1, None))
            # add the button to the grid layout
            self.layout.add_widget(btn)

        # create the scroll view
        self.scrll = ScrollView(size_hint=(1, .6), pos_hint={'center_x': .5, 'center_y': .5}, do_scroll_x=False)
        # add the grid layout to the scroll view
        self.scrll.add_widget(self.layout)
        # add everything (the scroll view) to the HOME menu
        self.add_widget(self.scrll)




class MyAppli(App):

    def build(self):
        Window.clearcolor = (1,1,1,1)
        return AppScreenManager()

Builder.load_file("debug.kv")
if __name__ == '__main__':
    MyAppli().run()

2 个答案:

答案 0 :(得分:1)

调用你传递给on_press会收到按钮实例作为它的参数:

class Home(Screen):
    def button_pressed(self, btn):
        print(btn.text)

    # ...

Button(text=number, on_press=self.button_pressed,  # ...

答案 1 :(得分:0)

其他(以及更好的恕我直言)方式:您可以创建自己的类MyButton作为Button类的子类并定义on_press()方法:

class MyButton(Button):

    numeric_property = NumericProperty(0)

    def __init__(self, numeric_property, **kwargs):
        super(MyButton, self).__init__(**kwargs)
        self.numeric_property = numeric_property

    def on_press(self):
        print self.numeric_property

然后你可以添加它:

for number in numbers:
    btn = MyButton(text=number, numeric_property=number, background_color=(.7, .7, .7, 1), color=(1,1,1,1), size=(32,32), size_hint=(1, None))
    self.layout.add_widget(btn)