【问题标题】:Kivy Taking user input from textinput and setting the text as a labelKivy 从 textinput 获取用户输入并将文本设置为标签
【发布时间】:2020-09-20 16:14:19
【问题描述】:

我看到很多非常相似的问题被问到,但似乎没有一个答案有效。我将一个程序剥离为非常基础的程序,但它似乎仍然无法正常工作,这是代码:

.kv 文件

WindowManager:
    FirstWindow:
    SecondWindow:
            
<FirstWindow>:

    name: 'first'

    GridLayout:
        cols: 1
        size: root.size

        GridLayout:
            cols: 2

            Label:
                text: 'Put some text'

            TextInput:
                id: item

            Button:
                on_release: app.root.current = 'second'
        
<SecondWindow>:
    name: 'second'

    BoxLayout:
        orientation: 'vertical'

        Label:
            id: bi
            text: root.manager.get_screen('first').ids.item.text

.py 文件 是非常基础的文件,没有可能与程序冲突的额外信息。因此,当我在标签中输入文本时,它会在 第二屏幕 上返回一个空字符串。有人可以帮忙吗?

【问题讨论】:

  • 问题可能是您的text: 行运行了一次并且从未重新评估,因为kv 解析器无法识别您指的是可以绑定到的东西。
  • 那么我可以在text 之后执行一行代码来重新评估该行吗?还是通过 .py 文件完成
  • 我会寻求以不同的方式实现您的结果。例如,您的 textinput 可能有 on_text: app.text = self.text,而您的 SecondWindow 可能有 text: app.text(当然,您还需要将 app.text 声明为 StringProperty)。这只是一个基本的解决方案,this page 包含更多替代方案。
  • 刚试过这个,我得到一个错误说AttributeError: 'ExampleApp' object has no attribute 'text'。当我使用text: app.text 行时?
  • 您是否做了“当然需要将 app.text 声明为 StringProperty”部分?这意味着在您的 App 类中写入 text = StringProperty()

标签: python kivy kivymd


【解决方案1】:

你的屏幕管理器看起来对我不熟悉,试试这个:

ma​​in.kv

<RootWidget>:
manager: manager
ScreenManager:
id: manager
pos_hint: {'top': 0.9}
Screen:
    name: 'Screen 1'
    TextInput:
        id: input1
        text: 'Type Here'
        size_hint: 0.2,0.1
        pos_hint: {'center_x':0.5,'center_y':0.6}
    Button:
        text: 'Move to screen 2'
        size_hint: 0.2,0.1
        pos_hint: {'center_x':0.5,'center_y':0.4}
        on_release: app.tmb1()

Screen:
    name: 'Screen 2'
    TextInput:
        id: input2
        text: 'Screen 2'
        size_hint: 0.2,0.1
        pos_hint: {'center_x':0.5,'center_y':0.6}
    Button:
        text: 'Move to screen 1'
        size_hint: 0.2,0.1
        pos_hint: {'center_x':0.5,'center_y':0.4}
        on_release: app.tmb2()        

ma​​in.py

from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import NumericProperty, ObjectProperty
from kivy.lang import Builder
from kivy.uix.floatlayout import FloatLayout


class RootWidget(FloatLayout):
    manager = ObjectProperty()

class MainApp(App):

    def build(self):
    return RootWidget()

def tmb1(self):
    self.root.ids['input2'].text=self.root.ids['input1'].text
    self.root.manager.current='Screen 2'

def tmb2(self):
    self.root.ids['input1'].text=self.root.ids['input2'].text
    self.root.manager.current='Screen 1'

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-08
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多