首页 > 解决方案 > 如何通过访问dict中的键或值来设置标签文本

问题描述

我想从 dict 访问密钥。这是一个文本输入。我给那个 textinput 一个 id:word。如果该文本输入中的任何文本与该字典中的任何这些键或值匹配,则应更改标签的文本以显示一些文本。我可以从 dict 访问键或值。

但问题是当我在 Dict.keys() 中使用 if self.ids.word 时:然后显示一些东西。但 self.ids.word 是一个字符串数据,任何来自 dict 的键或值都是 Nonetype 类。所以 self.ids.word 不能在 dict 中。导致 str 不能在 dict 中(而 dict 键或值 ls nonetype)

我怎样才能做到这一点?

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.properties import *

Dict={"my": "amar","i":"ami","you":"tumi"}


class pop(Popup):
    add=StringProperty()
    a=app.root.yo.ids.word.text
    if a in Dict.keys():
        self.add=str(a) + str(Dict.get(a))
class yo(BoxLayout):
    def pop(self):
        po=pop()
        po.open()
class go(BoxLayout):
    main=ObjectProperty(None)
    def yo(self):
        self.clear_widgets()
        self.main=yo()
        self.add_widget(self.main)

Builder.load_string('''
<go>:
    Button:
        text:"go"
        on_press:root.yo()
<yo>:
    TextInput:
        id:word
    Button:
        text:"press"
        on_press:root.pop()
<pop>:
    title:"pop"
    size_hint:0.8,0.3
    Label:
        text:root.add

''')

标签: pythondictionarykivy

解决方案


问题2

我想在弹出标签中获取这些密钥和 ID。我知道在 kivy 中我应该使用 a=app.root.yo.ids.word.text。但是如何在 py 代码中访问该 ID?

解决方案

  1. 实现类的构造函数pop()
  2. 用于App.get_running_app()获取您的应用程序的实例
  3. 用于root.main获取yo对象的实例

片段 - py 文件

class pop(Popup):
    add = StringProperty()

    def __init__(self, **kwargs):
        super(pop, self).__init__(**kwargs)
        a = App.get_running_app().root.main.ids.word.text
        if a in Dict.keys():
            self.add = str(a) + str(Dict.get(a))

问题 1

但问题是当我在 Dict.keys() 中使用 if self.ids.word 时:然后显示一些东西。但 self.ids.word 是一个字符串数据,任何来自 dict 的键或值都是 Nonetype 类。所以 self.ids.word 不能在 dict 中。导致 str 不能在 dict 中(而 dict 键或值 ls nonetype)

解决方案

self.ids.word是对TextInput对象的引用。因此,您要访问对象的text属性TextInput

替换a = self.ids.worda = self.ids.word.text


推荐阅读