KivyMD:如何在屏幕上从文件中写入文本

KivyMD: how to write text from file on screen

我是初学者,我尝试做一个应用程序作为笔记。用户可以在一个屏幕上写他们的提醒。它被写入一个文件,所以我在文件中有一个文本,我想在另一个屏幕上显示它。 我试过这样的东西,但它不起作用。谁能帮帮我?

class MyGoalsScreen (Screen):

   file= open("package.txt" , "r")
   load_file = ""
   for line in file:
       load_file = load_file + line
   file.close()

在 .kv 中

<MyGoalsScreen>:
   name: "mygoals"  
   
   MDToolbar:
       title: "My Goals"
       pos_hint: {"top": 1} 
       
   
   MDCard:
       orientation: "vertical"
       pos_hint:{ "center_x" :0.5, "center_y": 0.5} 
       size_hint: 0.8, 0.7
       padding: "8dp"

       MDLabel:
           text: f"{load_file} "
           halign: "center"
           font_size: (root.width**2 + root.height**2) / 13**4
           size_hint: 0.8, 0.1

load_file 变量在您的 python 代码中,不在您的 .kv 文件中。要从 python 文件访问某些内容,您必须使用 app.。所以,不要写 load_file,而是使用 app.load_file。此外,您必须在 py 文件的开头定义 load_file 。还有一件事,正如您在开始时定义 load_file 然后稍后更改它一样。有可能它不会在你的 kivy 文件中改变,因为数据已经加载到你的屏幕上。您必须为此刷新屏幕。我建议使用 python 在屏幕上添加文本。您可以为 MDLabel 提供 id,然后使用 id 更改文本。你必须像 self.root.ids.<MDLABEL_ID>.text = load_file.

那样做

你可以试试这个:-

.py代码

class MyGoalsScreen (Screen):
    def on_enter(self):
        file= open("package.txt" , "r")
        load_file = ""
        for line in file:
            load_file = load_file + line
        file.close()
        self.ids.mylabel.text = load_file

.kv码

<MyGoalsScreen>:
    name: "mygoals"  

    MDToolbar:
        title: "My Goals"
        pos_hint: {"top": 1} 
   

    MDCard:
        orientation: "vertical"
        pos_hint:{ "center_x" :0.5, "center_y": 0.5} 
        size_hint: 0.8, 0.7
        padding: "8dp"

    MDLabel:
        id: mylabel
        halign: "center"
        font_size: (root.width**2 + root.height**2) / 13**4
        size_hint: 0.8, 0.1

希望这能解决您的问题。