将屏幕与 kivy 中的 GridLayout 类相关联

2022-01-15 00:00:00 python kivy

问题描述

我创建了一个 ScreenManager,并为该 ScreenManager 创建了几个 Screen 实例.

I've created a ScreenManager, and created several Screen instances for that ScreenManager.

我希望每个屏幕都显示一个 GridLayout 类.例如,假设您有:

I'd like each Screen to display a GridLayout class. For example, let's say you have:

class MainScreen(Screen):
   ...

class MainLayout(GridLayout):
   ...

当 MainScreen 是活动屏幕时,我希望显示 MainLayout.

When MainScreen is the active screen, I'd like MainLayout to be shown.

有没有办法纯粹在 python 中做到这一点(即没有标记)?谢谢.

Is there a way to do this purely in python (i.e. without markup)? Thank you.


解决方案

有没有办法纯粹在 python 中做到这一点(即没有标记)?谢谢.

Is there a way to do this purely in python (i.e. without markup)? Thank you.

您永远不需要使用 kivy 语言(我假设这就是您所说的标记的意思),但强烈建议尽可能使用它,因为它使很多事情变得更容易.

You never need to use kivy language (I assume that's what you mean by markup), though it's highly recommended where possible because it makes lots of stuff easier.

不过,要真正回答您的问题,您只需将 gridlayout 小部件添加到屏幕小部件,例如

Nonetheless, to actually answer your question, all you have to do is add your gridlayout widget to your screen widget, something like

mainscreen = MainScreen()
mainlayout = MainLayout()
mainscreen.add_widget(mainlayout)

然后,当您在屏幕管理器中将当前屏幕设置为主屏幕时,您应该会看到 GridLayout.

Then when you set the current screen in your screenmanager to be mainscreen, you should see the GridLayout.

如果不清楚,这通常是您将小部件添加到其他小部件的方式.当你看到一个 kv 语言的例子时,比如

In case it's unclear, this is in general the way you add widgets to other widgets. When you see an example in kv language like

<MyScreen>:
     GridLayout:
         ...

...最终,它被翻译成与上面的示例代码非常相似的内容 - 创建了一个 MyScreen 实例,并使用 add_widget 向其中添加了一个 GridLayout.

...ultimately that gets translated to something much like the above example code - an instance of MyScreen is created and a GridLayout is added to it with add_widget.

相关文章