【问题标题】:How to save the path of a file obtained from the user in a Json file?如何将用户获取的文件路径保存在Json文件中?
【发布时间】:2021-10-21 21:04:20
【问题描述】:

我想将用户获取的图像文件的路径保存在 JSON 文件中,并根据路径更改图像。路径保存在JSON文件中是这样的,

{"PathInfo": {"cover_path": "\"E:\\K75 Programming\\Python\\Mode\\Photos\\2.jpg\""}}

因此图像不会改变。我想这样保存路径,

  • {"PathInfo": {"cover_path": "E:\K75 Programming\Python\Mode\Photos\2.jpg"}}

我认为图片会正确更改。那么,我该怎么做呢?

这是我的代码

from kivy.lang.builder import Builder
from kivy.uix.screenmanager import Screen
from kivymd.app import MDApp
from kivy.storage.jsonstore import JsonStore

screen_helper = """

ScreenManager:
    Studio:
    EditCover:
    
<Studio>:
    name : 'studio'
    MDFloatLayout:
        FitImage:
            id: cover_pic
            orientation: "vertical"
            size_hint: 1, .75
            pos_hint: {"center_x": .5, "center_y": 1}
            source: "Photos/3.jpg"
    
<EditCover>:
    name : 'edit_cover'
    MDTextField:
        id : cover_path
        hint_text: "Path"
        mode: "rectangle"
        pos_hint: {'center_x':0.5,'center_y':0.5}
        size_hint: (0.68,0.07)
    MDRaisedButton:
        text : 'OK'
        pos_hint : {'center_x':0.9,'center_y':0.08}
        font_style: 'Button'
        ripple_rad_default : 40
        ripple_duration_out : 1
        md_bg_color: app.theme_cls.primary_dark
        on_press : app.save_pic_path()
        
"""


class EditCover(Screen):
    pass


class Studio(Screen):
    pass


class Mode(MDApp):
    def build(self):
        return Builder.load_string(screen_helper)

    def save_pic_path(self):
        self.cover_path = self.root.get_screen('edit_cover').ids.cover_path.text
        self.store_paths.put('PathInfo', cover_path = self.cover_path)
        self.pic_changer()

    def pic_changer(self):
        self.root.get_screen('studio').ids.cover_pic.source = "{self.store_paths.get('PathInfo')['cover_path']}"

    def on_start(self):
        self.store_paths = JsonStore("paths.json")

        try:
            if self.store_paths.get('PathInfo')['cover_path'] != "":
                self.pic_changer()

        except KeyError as e:
            self.root.get_screen('studio').ids.cover_pic.source = "Photos/3.jpg"

Mode().run()

但是,我只想从用户那里获取路径并根据它更改图像。

  • 可以按照我想的方式正确完成吗?
  • 或者,有没有更好的方法来正确执行此操作?

请帮我完成这个项目。

【问题讨论】:

    标签: python json kivy kivymd


    【解决方案1】:

    如果你想将cover_path值分配给图片源,我想你忘了使用f-string表示法,如下代码:

    def pic_changer(self):
        self.root.get_screen('studio').ids.cover_pic.source = f"{self.store_paths.get('PathInfo')['cover_path']}"
    

    希望能帮到你

    【讨论】:

    • 哦!我已经忘记了。我没能找到问题。 @kuroaza 先生,非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多