首页 > 解决方案 > 尝试在 Kvlang 的 BoxLayout 中重新定位图像时出现问题

问题描述

我正在使用 Kivy 创建一个应用程序,我希望它在左角有一个带有图像的标题,并且在这个图像的右侧有一些按钮,如菜单。问题是我无法重新定位图像。我可以调整它的大小,但它的位置总是在 BoxLayout 的起始位置。

我试过用 pos_hint 和 pos 改变它的位置。还尝试使用 size_hint 调整图像大小或将 size_hint 设置为 (None, None) 并且他们尝试再次更改其位置并且它们都不起作用。我还在其下方的 ScrollView 上添加了一些按钮,当按下时会显示图像的位置以检查是否有效。这是 Kvfile,我只是粘贴出现此问题的 Screen(SomeScreen) 小部件

<SomeScreen>:
    BoxLayout:
        orientation: 'vertical'
        BoxLayout:
            id: box
            size_hint: 1, 0.12
            canvas:
                Rectangle:
                    size: self.size
                    pos: self.pos
            Image:
                id: img
                size_hint: None, 0.9
                width: 200
                pos: 200, 600
                allow_stretch: True
                source: 'image.png'


        ScrollView:
            id: scr
            BoxLayout:
                orientation: 'vertical'
                size_hint: 1, None
                height: self.minimum_height
                Button:
                    size_hint: None, None
                    width: 400
                    height: 200
                    on_press: print(f'image size: {img.size}, image postion {img.pos}')
                Button:
                    size_hint: None, None
                    width: 400
                    height: 200
                    on_press: print(box.size, box.pos)
                Button:
                    size_hint: None, None
                    width: 400
                    height: 200
                    on_press: print(scr.size, scr.pos)

我想将图像的位置更改为我选择的任何位置

标签: pythonkivykivy-language

解决方案


有几点需要注意:

  • 您正在使用BoxLayoutwith orientationset to vertical。这将垂直放置您的小部件,因此ScrollView 不会位于您的Image.

  • BoxLayout在你的第一个里面有BoxLayout一个
    看起来毫无用处的第二个。然而,把你Image
    horizontal(默认)BoxLayout,意味着你不能调整
    horizontal位置Image

不确定我是否已经捕捉到您的意图,但这是您的修改版本kv,我认为,它更符合您的要求:

<SomeScreen>:
    BoxLayout:
        Image:
            id: img
            size_hint: None, 0.12
            width: 200
            pos_hint: {'center_y':0.5}
            allow_stretch: True
            source: 'image.png'

        ScrollView:
            id: scr
            BoxLayout:
                orientation: 'vertical'
                size_hint: 1, None
                height: self.minimum_height
                Button:
                    size_hint: None, None
                    width: 400
                    height: 200
                    on_press: print(f'image size: {img.size}, image postion {img.pos}')
                Button:
                    size_hint: None, None
                    width: 400
                    height: 200
                    on_press: print(box.size, box.pos)
                Button:
                    size_hint: None, None
                    width: 400
                    height: 200
                    on_press: print(scr.size, scr.pos)

推荐阅读