从kivy、kv文件中的按钮制作标签

2024-05-05 20:24:01 发布

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

好的,看,有谁能在kivy.kv文件中给出一个例子,一个按钮被设置为一个命令,当你按下它时,它会在按钮下面做一个标签, 我试过了

Python

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.label import Label
Builder.load_file("my.kv")
class MyLayout(Widget,App):
    def __init__(self, **kwargs):
        super(MyLayout, self).__init__(**kwargs)

    def addthelabel(self):
        self.button = Label(text"you have just added me")
        self.add_widget(self.button)
class UiApp(App):
        def build(self):
            return MyLayout()
UiApp().run()

.kv文件

<MyLayout>:
    BoxLayout:
        orientation:"horizontal"
        size: root.width, root.height
        Button:
            text:"hello"
            on_press:
            root.addthelabel()

但当我运行它并点击按钮时,它并不是我所期望的 形象 https://i.stack.imgur.com/ZoOCj.png 所以我需要一个新的例子,你们能帮忙吗


Tags: 文件fromimportselfappdefrootwidget
1条回答
网友
1楼 · 发布于 2024-05-05 20:24:01

您看到此行为的原因是,在addthelabel()中,新的Label被添加为根MyWidget布局的子级,而不是添加到包含现有按钮的BoxLayout

要获得所需的行为,您需要在kv文件中的BoxLayout中添加一个id,该文件允许您从Python代码访问该小部件。您还需要将orientation更改为vertical

<MyLayout>:
    BoxLayout:
        id: layout
        orientation:"vertical"
        size: root.width, root.height
        Button:
            text:"hello"
            on_press: root.addthelabel()

然后在Python代码中,我们不想将新的Label添加到根小部件,而是想使用它的新id将它添加到BoxLayout

from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.uix.label import Label
Builder.load_file("my.kv")
class MyLayout(Widget,App):
    def __init__(self, **kwargs):
        super(MyLayout, self).__init__(**kwargs)

    def addthelabel(self):
        self.button = Label(text="you have just added me")
        self.ids.layout.add_widget(self.button)
class UiApp(App):
        def build(self):
            return MyLayout()
UiApp().run()

相关问题 更多 >