简体   繁体   中英

how to set label text by accessing key or value from dict

i want to acces key from dict. here's a textinput. i gave that textinput an id:word. if any text from that textinput matches any of these key or value from that dict, then the text of a label should be changed to show some text. i can access key or value from dict.

but problem is when i use if self.ids.word in Dict.keys(): then show something. but self.ids.word is a string data and any key or value from dict is Nonetype class. so self.ids.word cant be in dict. cause str cant be in dict(while dict key or value ls nonetype)

how can i do that?

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

''')

Question 2

i want to get these key and ids in a popup label. i know in kivy i should use a=app.root.yo.ids.word.text. but how to access that id in py code?

Solution

  1. Implement a constructor for class pop() .
  2. Use App.get_running_app() to get an instance of your app
  3. use root.main to get an instance of your yo object

Snippets - py file

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))

Question 1

but problem is when i use if self.ids.word in Dict.keys(): then show something. but self.ids.word is a string data and any key or value from dict is Nonetype class. so self.ids.word cant be in dict. cause str cant be in dict(while dict key or value ls nonetype)

Solution

self.ids.word is a reference to the TextInput object. Therefore, you want to access the text attribute of the TextInput object.

Replace a = self.ids.word with a = self.ids.word.text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM