You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Kivy中Label与TextInput文本位置对齐问题求助

问题解决:Kivy中Label与透明TextInput文本精准对齐实现选中功能

问题说明

需要实现:将透明TextInput覆盖在Label上方,让二者文本位置、尺寸完全一致,从而通过TextInput的选中功能来选中Label的文本。当前遇到的问题是二者文本位置偏移,无法精准对齐。

解决方案代码

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.floatlayout import FloatLayout

class main(App):
    def build(self):
        f = FloatLayout()

        # 配置Label,限制宽度为400
        label = Label(
            text="The quick brown fox jumps over the lazy dog",
            text_size=(400, None),
            markup=True,
            font_size="24",
            size=(400, 100),
            pos=(100, 100),
            size_hint=(None, None)
        )

        # 配置TextInput,与Label完全对齐
        textinput2 = TextInput(
            text="The quick brown fox jumps over the lazy dog",
            font_size="24",
            size=(400, 100),
            pos=(100, 100),
            size_hint=(None, None),
            readonly=True,
            # 透明背景,仅保留选中时的反馈
            background_color=(0, 0, 0, 0),
            # 文本透明,让下方Label显示出来
            foreground_color=(0, 0, 0, 0),
            # 关键:设置text_size与Label一致,确保换行规则相同
            text_size=(400, None),
            # 消除默认内边距,让文本位置和Label对齐
            padding=(0, 0),
            # 禁用光标,避免干扰视觉
            cursor_color=(0,0,0,0)
        )

        # 先添加Label,再添加TextInput,确保TextInput覆盖在上方
        f.add_widget(label)
        f.add_widget(textinput2)

        return f

main().run()

关键修改点说明

  • 给TextInput设置text_size=(400, None),与Label保持一致,确保文本的换行和布局规则完全相同
  • 设置padding=(0, 0),消除TextInput默认的内边距,避免文本偏移
  • 调整background_color和foreground_color为全透明,只保留TextInput的选中交互功能,让下方的Label文本正常显示
  • 禁用光标,避免干扰视觉效果
  • 调整添加顺序:先添加Label再添加TextInput,确保TextInput覆盖在Label上方

内容的提问来源于stack exchange,提问作者Mango

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 16:02:50