首页 > 解决方案 > Kivy 按钮不显示

问题描述

根据我在 youtube 视频中看到的这段代码,kivy 屏幕中显示了两个并排的按钮,但在我的情况下,屏幕是空白的。没有按钮显示。提前感谢您的帮助。我是 Python 和 kivy 的新手。

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget


class BoxLayoutExample(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        b1 = Button(text="Button A")
        b2 = Button(text="Button B")
        self.add_widget(b1)
        self.add_widget(b2)


class MainWidget(Widget):
    pass


class TheLabApp(App):
    pass


TheLabApp().run()

标签: pythonkivy

解决方案


这应该可以;)问题是您刚刚在 TheLabApp 类中输入了“pass”。当您使用 .kv 文件时,这可能有效,但您不是我所看到的。

class TheLabApp(App):
    def build(self):
        return BoxLayoutExample()

您应该查看文档 ( https://kivy.org/doc/stable/api-kivy.app.html ) 以了解您的代码为何不起作用。他们给出了很好的例子。

编辑:

当您使用 .kv 文件时,您应该像这样工作:首先,将您的 .kv 文件命名为您的应用程序名称 (TheLabApp.kv)

.kv

BoxLayoutExample:

<TheLabApp>:
    BoxLayoutExample:

.py

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.widget import Widget


class BoxLayoutExample(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        b1 = Button(text="Button A")
        b2 = Button(text="Button B")
        self.add_widget(b1)
        self.add_widget(b2)


class MainWidget(Widget):
    pass

class TheLabApp(App):
    pass


TheLabApp().run()

推荐阅读