Kivy:从另一个类中的小部件检索文本?

2024-04-20 13:19:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从另一个类(这里是“GetInfoFromAnotherClass”)访问一个类(这里是“UserInput”)的TextInput.text。但是,“检索信息”按钮仅提供初始输入,不进行更新。而在类“UserInput”中,则没有问题-->;按钮“获取信息”。无论我在文本字段中输入什么,“检索信息”按钮总是返回“第一次输入”。我不知道该用谷歌搜索什么了。希望你们能帮帮我

下面是我的问题的一个“接近最小”的例子:

import kivy
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout


class Container(GridLayout):
    pass

class UserInput(BoxLayout):
    first_input = ObjectProperty(None)
    second_input = ObjectProperty(None)

    def __init__(self,**kwargs):
        super().__init__(**kwargs)

    def ui_btn(self):
        print(self.first_input.text)
        print(self.second_input.text)


class GetInfoFromAnotherClass(BoxLayout):
    def __init__(self,**kwargs):
        super().__init__(**kwargs)
        self.ui = UserInput()

    def retrieve_info(self):
        print(self.ui.first_input.text)
        print(self.ui.second_input.text)


class MainApp(App):
    def build(self):
        return Container()

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

和主电压(千伏):

#:kivy 1.11.0

# Well this is just for Beauty ;-)
<MyTextInput@TextInput>:
    size_hint_y: None
    height: 50
    multiline: False
    write_tab: False

<MyButton@Button>:
    size_hint_y: None
    height: 50

<Container>:

    cols: 1

    UserInput
    GetInfoFromAnotherClass

<UserInput>:
    first_input: first_input
    second_input: second_input
    size_hint_y: None
    height: self.minimum_height
    padding: 20

    MyTextInput:
        id: first_input
        text: "First Entry"

    MyTextInput:
        id: second_input
        text: "Second Entry"

    MyButton:
        text: "Get Info in the same class"
        on_press: root.ui_btn()

<GetInfoFromAnotherClass>:
    size_hint_y: None
    height: self.minimum_height
    padding: 20

    MyButton:
        text: "Retrieve Info from another Class"
        on_press: root.retrieve_info()

Tags: textfromimportselfnoneuiinputdef
1条回答
网友
1楼 · 发布于 2024-04-20 13:19:05

self.ui = UserInput()调用创建了一个没有人使用的UserInput实例

访问文本框的一种方法是:

  • 首先给你的UserInput实例一个id
<Container>:
    cols: 1
    UserInput:
        id: user_input_box
    GetInfoFromAnotherClass:
  • 创建存储当前运行的应用程序的变量
class GetInfoFromAnotherClass(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.app = App.get_running_app()
        # self.ui = UserInput()
  • 之后,使用下面的代码访问文本
    def retrieve_info(self):
        print(self.app.root.ids.user_input_box.ids.first_input.text)
        print(self.app.root.ids.user_input_box.ids.second_input.text)

相关问题 更多 >