将标签的文本更改为json文件中的值,但是当我运行程序时,标签为空

问题描述 投票:1回答:1

我是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个回答
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()

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

<Lab>:
    BoxLayout:
        Label:
            id: L
            text: root.the_value
        Label:
            text: "something"
© www.soinside.com 2019 - 2024. All rights reserved.