当要添加另一个屏幕按钮时。。。基维

2024-06-16 12:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如何将主页面中的imagebutton添加到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)

我正在尝试随机添加按钮到“btnsbox”在SPage根据哪个按钮被按下。。。换个开关好吗?任何类型的输入都会有帮助,我愿意学习。谢谢您!在


Tags: selfadddefargs页面widgetscreen按钮
1条回答
网友
1楼 · 发布于 2024-06-16 12:27:09

我会将新按钮添加到列表中,并使用random的shuffle来洗牌它们。然后清除第二个屏幕上的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()

相关问题 更多 >