按下时按钮添加到另一个屏幕... kivy

时间:2017-02-27 12:49:11

标签: python kivy

如何将MainPage中的图像按钮添加到SPage?

例如:

class MainPage(Screen):
    def openmain(self, *args):
        self.stop = ImageButton(source= 'stop.png', allow_stretch= True, pos= (390, 300), size_hint= (.2,.1))
        self.stop.bind(on_release=self.addstop)
        self.add_widget(self.stop)
        #btn2
        #btn3
        #btn4

class SPage(Screen):
    def buttonsbox(self, *args):
        for x in xrange(4): ####how do I use choice(random)
            self.btnsbox = BoxLayout(orientation= 'vertical')
            self.add_widget(self.btnsbox)

我正在尝试将按钮随机添加到SPage中的“btnsbox”,根据哪一个按下...会像交换机那样工作吗?任何类型的输入都会有所帮助,我愿意学习。谢谢!

1 个答案:

答案 0 :(得分:1)

我会将新按钮添加到列表中,并使用随机播放来随机播放它们。然后清除第二个屏幕上的boxlayout,并通过列表循环,将它们附加到boxlayout。
试试这个例子:

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager
from kivy.lang import Builder
from kivy.properties import ListProperty, ObjectProperty
from random import shuffle



Builder.load_string('''

#: import Button kivy.uix.button.Button

<MyScreenManager>:
    box2: box2
    Screen:
        name: "screen1"
        BoxLayout:
            orientation: "vertical"
            Button:
                text: "Button 1"
                on_release:
                    root.added_buttons.append(Button(text="Button 1"))
            Button:
                text: "Button 2"
                on_release:
                    root.added_buttons.append(Button(text="Button 2"))
            Button:
                text: "Button 3"
                on_release:
                    root.added_buttons.append(Button(text="Button 3"))
            Button:
                text: "Goto screen 2"
                on_release: root.current = "screen2"

    Screen:
        name: "screen2"
        on_enter: root.update_buttons()
        BoxLayout:
            orientation: "vertical"
            BoxLayout:
                orientation: "vertical"
                id: box2
            Button:
                text: "Goto screen 1"
                on_release:
                    root.current = "screen1"

''')



class MyScreenManager(ScreenManager):

    box2 = ObjectProperty(None)
    added_buttons = ListProperty([])


    def update_buttons(self,*args):

        self.box2.clear_widgets()
        shuffle(self.added_buttons)
        for i in self.added_buttons:
            self.box2.add_widget(i)
        self.added_buttons[:] = []



class MyApp(App):

    def build(self):

        return MyScreenManager()



MyApp().run()