首页 > 解决方案 > 如何使用第二个屏幕从 kivy 的文本字段中提取文本?

问题描述

我最近开始学习 python 和 kivy,出于某种原因,我一直在学习

AttributeError: 'super' object has no attribute '__getattr__'

目前我拥有的代码只是用于测试它,我知道存在其他类似的帖子,但我已经按照他们正在做的事情来修复它,我一直收到同样的错误。

这部分是text.py

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

Builder.load_file('text.kv')


# Declare both screens
class MenuScreen(Screen):
    pass


class WritingScreen(Screen):
    pass


# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(WritingScreen(name='Write'))
screens = [Screen(name='Title {}'.format(i)) for i in range(2)]




class TestApp(App):

    def build(self):
        return sm

    def write(self):
        sm.current = 'Write'

    def process(self):
        text = self.root.ids.input.text
        print("Hello")


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

这是我的 Text.kv 文件

<MenuScreen>:
    FloatLayout:
        Button:
            text: 'Write'
            on_press: app.write()
            size_hint: .3, .2
            background_color: 1, 2, 1, 1
            pos_hint: {'x': .35, 'y': .4}
<WritingScreen>:
    FloatLayout:
        TextInput:
            id: input
            hint_text: "Ello There... Yaren't supposed to be here yet..."
            size_hint: .8, .1
            pos_hint: {'x':0, 'y': 0.9}
        Button:
            text: 'print'
            on_press: app.process()
            size_hint: .2, .1
            pos_hint: {'x':.8, 'y': .8}
        Button:
            text: 'Back to menu'
            on_press: root.manager.current = 'menu'
            size_hint: .2, .1
            pos_hint: {'x':.8, 'y': .9}

如果这是一个重复的问题,我再次感到很抱歉,但我尝试过的每一篇文章都对我不起作用。感谢您的所有帮助,我仍然是初学者,如果有任何提示,我将不胜感激!:)

标签: pythonkivykivy-language

解决方案


您在process()方法中的行:

text = self.root.ids.input.text

试图使用 the input id,就好像它在idsof the root(即 the ScreenManager)中一样,但是字典是在定义它们ids的规则的根中设置的。kv所以input id是在idsWritingScreen。要访问idsWritingScreen您可以将该行代码更改为:

text = self.root.get_screen('Write').ids.input.text

推荐阅读