【问题标题】:Kivy - re-focusing input field not possible?Kivy - 无法重新聚焦输入字段?
【发布时间】:2021-03-19 21:35:40
【问题描述】:

我有以下使用 kivy 的示例 -

当我在输入字段 1 中写入内容并按重置时 - 一切正常(输入字段被删除,专注于字段 1)。 但是当我在 field2 中更改某些内容并按下重置按钮时,似乎应用程序被破坏了......

为什么会这样?为什么 self.ids.stockTicker.focus = True 语句每次都不起作用?

py 文件:

import threading
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.lang import Builder
from kivy.core.window import Window


Builder.load_file("TryApp.kv")

class MyLayout(Widget):
    Window.size = (550, 700)

    def Reset(self):
        self.ids.stockTicker.text = ""
        self.ids.stockTicker.focus = True
        self.ids.index.text = "SP500"

    def pressReset(self):
        threading.Thread(target=self.Reset).start()

class MyTry(App):
    def build(self):
        return MyLayout()

if __name__ == "__main__":
    MyTry().run()

kv 文件:

<MyLayout>
    BoxLayout:
        orientation: "vertical"
        size: root.width, root.height

        GridLayout:
            size_hint: (1, .5)
            cols: 2
            Label:
                text: "Field1"
                font_size: 18
            TextInput:
                id: stockTicker
                focus: True
            Label:
                text: "Field2"
                font_size: 18
            TextInput:
                id: index
                text: "xyz"

        Button:
            id: buttonReset
            text: "Reset"
            #font_size: 20
            on_press: root.pressReset()
            size_hint: (None,None)
            width: 110
            height: 70

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    我认为你只需要改变:

            on_press: root.pressReset()
    

    到:

            on_release: root.pressReset()
    

    原因是当pressReset()方法被on_press事件触发时,焦点会随心所欲地改变,但随后Button释放事件会将焦点改变回Button。将其更改为 on_release 事件可以消除该问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-19
      • 1970-01-01
      相关资源
      最近更新 更多