【问题标题】:change the text of label to a value from a json file, but when I run the program the label is blank将标签的文本更改为 json 文件中的值,但是当我运行程序时,标签为空白
【发布时间】:2018-03-01 14:31:41
【问题描述】:

我是 python 和 kivy 的新手。我正在尝试制作一个小程序,其中标签的文本将是来自 vocab_words.json 的值

但是我得到一个空白标签,我认为即使我已经调用了 inpuut() 函数,它仍在运行。 请告诉我我的代码有什么问题和 还有我怎样才能将标签的文本更改为 json 文件中的值。

这是我的代码:

import kivy
kivy.require('1.10.0')

from kivy.uix.label import Label
from kivy.app import App 
from kivy.uix.widget import Widget
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout

class Lab(BoxLayout):
    the_value= StringProperty()     
    def  inpuut(self):
        with open('vocab_words.json') as rfile:
            data=json.load(rfile)

        the_value=data[0]['word']


class main(App):
    def build(self):
        return Lab()

m = main()
m.run()

这里是 kivy 代码:

<Lab>:

    BoxLayout:
        Label:
            id: L
            on_text:root.inpuut()
            text: root.the_value
        Label:
            text: "something"

我将不胜感激。

【问题讨论】:

    标签: python kivy


    【解决方案1】:

    on_text 属性不存在,因此无济于事。对于您的情况,有两种可能性:

    • 使用函数分配文本:

    *.py

    import kivy
    kivy.require('1.10.0')
    
    from kivy.app import App 
    from kivy.uix.boxlayout import BoxLayout
    import json
    
    class Lab(BoxLayout):   
        def  inpuut(self):
            with open('vocab_words.json') as rfile:
                data=json.load(rfile)
                return data[0]['word']
    
    class main(App):
        def build(self):
            return Lab()
    
    m = main()
    m.run()
    

    *.kv

    <Lab>:
        BoxLayout:
            Label:
                id: L
                text: root.inpuut()
            Label:
                text: "something"
    
    • 或使用StringProperty:

    *.py

    import kivy
    kivy.require('1.10.0')
    
    from kivy.app import App 
    from kivy.properties import StringProperty
    from kivy.uix.boxlayout import BoxLayout
    import json
    
    class Lab(BoxLayout): 
        the_value= StringProperty()     
        def  __init__(self, *args):
            BoxLayout.__init__(self, *args)
            with open('vocab_words.json') as rfile:
                data=json.load(rfile)
                self.the_value = data[0]['word']
    
    class main(App):
        def build(self):
            return Lab()
    
    m = main()
    m.run()
    

    *.kv

    <Lab>:
        BoxLayout:
            Label:
                id: L
                text: root.the_value
            Label:
                text: "something"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 2023-04-07
      • 2011-07-04
      相关资源
      最近更新 更多