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

2024-06-16 15:04:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我是begginer,我尝试制作一个应用程序作为笔记。用户可以在一个屏幕上编写提醒。。它被写入一个文件,所以我在文件中有一个文本,我想在另一个屏幕上显示它。 我试过类似这样的方法,但不起作用。有人能帮我吗

class MyGoalsScreen (Screen):

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

单位:千伏

<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

Tags: 文件用户pos应用程序size屏幕lineload
2条回答

你可以试试这个:-

.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

我希望这能解决你的问题

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

相关问题 更多 >