【问题标题】:kivy add a button to a specific location when pressing another buttonkivy 在按下另一个按钮时将按钮添加到特定位置
【发布时间】:2016-02-10 15:38:51
【问题描述】:

我有一个带有两个屏幕的 kivy/python 设置,我想在按下“添加按钮”按钮时添加一个新按钮,并且我想将新按钮添加到特定位置。添加按钮在屏幕二上,我希望新按钮出现在同一屏幕的 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'

谢谢, 马尔科

【问题讨论】:

    标签: python-2.7 kivy


    【解决方案1】:

    如果你想创建一个执行特殊操作的按钮,你应该在 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 代码中的按钮。

    【讨论】:

    • 我不得不使用 self.ids.grid_1.add_widget 而不是 self.root.ids... 但它很好地解决了问题
    【解决方案2】:

    只需告诉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'
    

    请注意,我删除了grid_1rows 属性,否则新按钮将没有空间。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多