【问题标题】:Kivy Selection on FocusKivy 选择焦点
【发布时间】:2020-04-02 06:05:05
【问题描述】:

我试图让 kivy 在焦点上选择 TextInput 小部件的文本,但是当我尝试它时,它似乎在取消焦点并保留选择时选择了它。有什么想法我可以在焦点上选择它并在取消焦点时选择它吗?如果有人想玩,我在下面附上了我的代码。

kv 文件:

<TextInput>:
    size_hint: 0.9, 0.5
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}
    multiline: False

<Button>:
    text: "Press Me"
    size_hint: (0.1, 0.5)
    pos_hint: {'center_x': 0.5, 'center_y': 0.5}

<MainLayout>:
    canvas.before:
        Color:
            rgba: 0.15, 0.15, 0.16, 1
        Rectangle:
            pos: self.pos
            size: self.size

    BoxLayout:
        orientation: 'vertical'
        padding: 10

        BoxLayout:
            padding: 10
            TextInput:
                text: "Directory"
            Button:
                text: "Browse"
                on_press: root.browse_btn()

        BoxLayout:
            padding: 10
            TextInput:
                text: "Prefix"
                on_focus: self.select_all()
            TextInput:
                text: "File"
                on_focus: self.select_all()
            TextInput:
                text: "Suffix"
                on_focus: self.select_all()

        BoxLayout:
            padding: 10
            Button:
                id: button_one
                text: "Confirm"
                on_press: root.confirm_btn()
            Button:
                text: "Cancel"
                on_press: root.cancel_btn()

python 文件:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.core.window import Window
from kivy.config import Config

Config.set('graphics', 'resizable', 0)


class MainLayout(BoxLayout):
    button_id = ObjectProperty(None)

    def browse_btn(self):
        print("Hey")

    def confirm_btn(self):
        print("Confirm")

    def cancel_btn(self):
        print("Cancel")


class BatchRenameApp(App):
    def build(self):
        self.title = "Batch File Rename"
        Window.size = (750, 250)
        return MainLayout()


if __name__ == '__main__':
    app = BatchRenameApp()
    app.run()

【问题讨论】:

    标签: python kivy kivy-language


    【解决方案1】:

    很好地隐藏在 TextInput 文档中:

    当 TextInput 获得焦点时,选择被取消。如果你需要显示 当 TextInput 聚焦时选择,你应该延迟(使用 Clock.schedule) 调用选择文本的函数 (select_all, select_text)。

    所以,在您的 kv 中,首先导入 Clock

    #: import Clock kivy.clock.Clock
    

    然后你可以在TextInput规则中使用它:

            TextInput:
                text: "Prefix"
                on_focus: Clock.schedule_once(lambda dt: self.select_all()) if self.focus else None
    

    if self.focus 确保 select_all 仅在 TextInput 获得焦点时发生。

    【讨论】:

    • 是的,如何管理它并不是很明显。我最初确实有时钟功能,但它在做同样的事情绝对没有想到添加 if 语句,但这解决了我的问题!谢谢!
    猜你喜欢
    • 2020-07-25
    • 2013-02-15
    • 1970-01-01
    • 2016-01-15
    • 2016-07-18
    • 1970-01-01
    • 2021-06-02
    • 2021-09-09
    • 2017-07-19
    相关资源
    最近更新 更多