在 Kivy 中做一个 ModalView 子类会弄乱视图的位置 children

Doing a ModalView subclass in Kivy messes up position of view and children

我有一个非常简单的 window 案例,只有一个按钮。通过释放按钮,我想弹出一个带有一些文本的模式视图。在每个按钮释放中,我创建并打开 ModalView 的实例并且它有效:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.modalview import ModalView
from kivy.uix.label import Label

class AButton(Button):
    def on_release(self, *largs):
        view = ModalView(size_hint=(None, None), size=[200, 200])
        view.add_widget(Label(text='I am a modal view'))
        view.open()


class MyApp(App):
    def build(self):
        return AButton()


if __name__ == '__main__':
    MyApp().run()

现在假设我想创建 ModalView 的子类,这样我就不必在每次弹出模态视图时都指定 size_hintsize。这是更改后的代码:

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.modalview import ModalView
from kivy.uix.label import Label
from kivy.properties import ListProperty

class AButton(Button):
    def on_release(self, *largs):
        view = ModalView2()
        view.add_widget(Label(text='I am a modal view'))
        view.open()


class ModalView2(ModalView):
    size_hint = ListProperty([None, None])
    size = ListProperty([200, 200])

    def __init__(self, **kwargs):
        super(ModalView2, self).__init__(**kwargs)


class MyApp(App):
    def build(self):
        return AButton()


if __name__ == '__main__':
    MyApp().run()

ModalViewLabel 位置完全搞砸了。我尝试在 ModalView2 中使用 anchor_xanchor_y 尝试修复标签位置,但没有成功。我做错了什么?

ModalView已经有size_hintsize属性,所以你不需要创建新的,只需将现有属性设置为你想要的值即可:

class ModalView2(ModalView):

    def __init__(self, **kwargs):
        super(ModalView2, self).__init__(**kwargs)
        self.size_hint = (None, None)
        self.size = (200, 200)