python - 如何通过访问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
''')
解决方案
问题2
我想在弹出标签中获取这些密钥和 ID。我知道在 kivy 中我应该使用 a=app.root.yo.ids.word.text。但是如何在 py 代码中访问该 ID?
解决方案
- 实现类的构造函数
pop()
。 - 用于
App.get_running_app()
获取您的应用程序的实例 - 用于
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.word
为a = self.ids.word.text
推荐阅读
- javascript - 使用 Javascript 从其 URL 获取网站的正文
- javascript - 有没有办法准确知道队列中的最后一个任务何时开始在多线程应用程序中?
- javascript - 尝试将表单值发送到 Firebase 时无法读取未定义的属性“preventDefault”
- python - Selenium - Python 脚本可从 CLI 运行,但使用 cron 启动时出错
- accessibility - 辅助功能 (JAWS) - 带有 Jquery Searchable-Multi-select-jQuery-Dropdown 的下拉列表
- google-sheets - 始终最多有 10 个值,最后一个值在 B1 中,而 A1 中的值消失
- typescript - 属性“x”没有初始值设定项,也没有在构造函数中明确分配。(2564)
- ruby-on-rails - Pgbouncer 优雅终止退出并删除插入
- macos - MacOS:确定任何窗口应用程序在哪个监视器上?
- swift - SwiftUI,Firestore 获取对象内的对象数组