使用 size_hint 时 Kivy 按钮文本消失

问题描述 投票:0回答:1

这里是新手程序员。尝试在我的 python/kivy 应用程序中实例化一个按钮,每当我设置 size_hint 时,按钮文本就会消失。目标是有一个窗口大小为 0.1 x 0.1 的按钮,并让它显示文本。

这是我的 python 文件(最小可重现错误):

from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.core.window import Window


class GameScreen(Widget):
    pass


class test801App(App):
    def build(self):
        return GameScreen()


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

这是我的 .kv 文件:

#:kivy 2.3.0

<GameScreen>:
    canvas:
        Color:
            rgba: 0, 0, 1, 1  # Blue (For the border)
        Rectangle:
            pos: root.x, root.y
            size: root.width, root.height
        Color:
            rgba: 1, 1, 1, 1  # White
        Rectangle:
            pos: root.x + 5, root.y + 5
            size: root.width - 10, root.height - 10

    FloatLayout:
        pos: 0,0
        size: root.width, root.height

        Button:
            pos_hint: {'x': .05, 'y': .05 }
            #size_hint: root.width * 0.1, root.height * .1
            font_size: 22
            bold: True
            background_normal: ''
            background_color: 0.2, 0.7, .2, 1 # Green
            color: 1, 0, 0, 1  # Red
            text_box_size: self.width, self.height
            text: 'Hello'

注释掉“size_hint”后,我得到了文本。当我取消注释该行时,文本就会消失。

当 Button 是 GridLayout 的一部分时(它是与画布处于同一级别的 FloatLayout 的一部分),它可以工作。当我直接将 Button 实例化为 FloatLayout 的一部分时,它停止工作。

我尝试添加 text_box_size 约束以确保它不会在窗口外显示文本。我尝试更改文字颜色。我尝试更改背景颜色。我尝试添加/删除background_normal。

顺便说明一下,size_hint 也不会使按钮变为 0.1x0.1。当 Button 是 GridLayout 的一部分时,这也有效。我还没有尝试调试这个问题,可能是相关的???

python button text kivy
1个回答
0
投票

size_hint
不是像素值,它是容器大小的一小部分。尝试更换:

size_hint: root.width * 0.1, root.height * .1

与:

size_hint: 0.1, 0.1

请参阅文档

© www.soinside.com 2019 - 2024. All rights reserved.