【问题标题】:Not set focus when come back screen manager with kivy and python使用 kivy 和 python 返回屏幕管理器时未设置焦点
【发布时间】:2019-10-13 21:35:59
【问题描述】:

我想在文本输入中设置焦点。开始时焦点设置正确,但是当我进入下一个屏幕并返回初始屏幕时,焦点设置不正确。

这是一个带有 rfid 讲师的应用程序,我想读取代码并选择进入或退出

ma​​in.py


import kivy
kivy.require('1.10.0') # replace with your current kivy version !


from kivy.app import App
from kivy.core.window import Window
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder

class MyScreenManager(ScreenManager):
    def __init__(self,**kwargs):
        super(MyScreenManager,self).__init__()


class Menu1(Screen):
    def __init__(self, **kwargs):
        super(Menu1, self).__init__()


class Menu2(Screen):
    def __init__(self, **kwargs):
        super(Menu2, self).__init__()


Builder.load_file("main.kv")


class Fichaje(App):
    def build(self):
        return MyScreenManager()


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

ma​​in.kv


#:kivy 1.10.0
#:import WipeTransition kivy.uix.screenmanager.WipeTransition

<MyScreenManager>:  
    #transition: WipeTransition()
    Menu1:
        id: menu1       
    Menu2:
        id: menu2


<Menu1>:
    name: "screen1"
    BoxLayout:
        orientation: 'vertical'
        TextInput:
            id: input1
            size_hint_y: .1
            multiline: False
            focus: True
            on_text_validate:                
                root.manager.current = "screen2"

        BoxLayout:  


<Menu2>:
    name: "screen2"
    BoxLayout:
        Button:
            text:"Entrada"          
            on_press:          
                root.manager.current = "screen1"

        Button:
            text:"Salida"
            on_press:       
                root.manager.current = "screen1"

没有错误消息但焦点不在正确的站点上, 谢谢

我更改代码以简化错误

【问题讨论】:

  • 这个例子包含两个以上的带有文本输入的屏幕。那有必要吗? stackoverflow.com/help/minimal-reproducible-example
  • label 和clocklabel 是必须的,第二个屏幕有两个按钮,按一个按钮返回第一个屏幕。您可以在 python 代码中看到的其他内容将来会很有用。谢谢!
  • 没问题,只是一个提示。如果您想快速获得答案,请将您的示例简化到您的问题所在。并且仍然可以运行。
  • def LimpiaInput(self): self.ids.TxtCodigo.text = "" self.ids.TxtCodigo.focus = True
  • @el3ien 我改了代码,你能帮帮我吗?

标签: python kivy focus screen


【解决方案1】:

在示例中,没有尝试更改焦点。但我认为这是尝试过的,但它再次失去了焦点。
文本输入再次失去焦点的原因是因为它在释放鼠标或点击之前获得焦点。 on_press 方法后跟 on_release 文本输入再次失去焦点。
要解决此问题,您只需在 on_release 方法中设置焦点即可。

最快的方法是只在kv文件中添加一行代码,将on_press改为on_release

root.manager.get_screen("screen1").ids["input1"].focus

例如,可以通过使用 screen1 中的对象属性来改变这一行。或者如果您不能使用on_release 方法,则可以使用时钟在一段时间内安排焦点,如果触摸仍然向下,请重新安排。
但这是快速修复。

<Menu2>:
    name: "screen2"
    BoxLayout:
        Button:
            text:"Entrada"
            on_release:
                root.manager.current = "screen1"
                root.manager.get_screen("screen1").ids["input1"].focus = True

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-04
    相关资源
    最近更新 更多