当按下另一个按钮

时间:2016-02-10 15:38:52

标签: python-2.7 kivy

我有一个带有两个屏幕的kivy / python设置,我想在按下“添加按钮”按钮时添加一个新按钮,我想将新按钮添加到特定位置。添加按钮位于屏幕2上,我希望新按钮出现在同一屏幕的GridLayout中。 我的python代码是:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

from kivy.uix.button import Button
from kivy.uix.widget import Widget



class MainScreen(Screen):
    pass

class AnotherScreen(Screen):
    pass

class ScreenManagement(ScreenManager):
    pass

class myApp(App):
    def build(self):
        pass
myApp().run()

kv文件看起来像这样:

ScreenManagement:
    MainScreen:
    AnotherScreen:

<MainScreen>:
    name: 'main'
    GridLayout:
        id:grid_1
        cols:2
        rows:1
        Button:
            on_release: app.root.current = 'other'
            text: 'Another Screen'
<AnotherScreen>:
    name: 'other'
    BoxLayout:
        id:box_1
        GridLayout:
            id:grid_1
            rows:2
            cols:1
            Button:
                on_release: app.root.current = 'main'
                text: 'back to the home screen'
            Button:

                text: 'new buttons appear here..'
        Button:
            id:Add_buttons
            on_release: ????
            text: 'Add button'

感谢, 马尔科

2 个答案:

答案 0 :(得分:0)

如果要创建执行特殊操作的按钮,则应在main.py文件中定义:

class MyButton(Button):
    def on_release(self):  # or on_press
        new_button = Button(text='hello')
        self.root.ids.grid_1.add_widget(new_button)

现在,替换kv代码中的按钮。

答案 1 :(得分:0)

告诉GridLayout添加新的小部件:

#: import Button kivy.uix.button.Button
ScreenManagement:
    MainScreen:
    AnotherScreen:

<MainScreen>:
    name: 'main'
    GridLayout:
        id:grid_1
        cols:2
        rows:1
        Button:
            on_release: app.root.current = 'other'
            text: 'Another Screen'
<AnotherScreen>:
    name: 'other'
    BoxLayout:
        id:box_1
        GridLayout:
            id:grid_1
            cols:1
            Button:
                on_release: app.root.current = 'main'
                text: 'back to the home screen'
        Button:
            id:Add_buttons
            on_release: grid_1.add_widget(Button(text='new button'))
            text: 'Add button'

请注意,我删除了rows的{​​{1}}属性,否则就不会有新按钮的空间。