首页 > 解决方案 > Python3 - 如何在 kivymd 中加载文件?(并将其路径存储为字符串)

问题描述

使用 kivymd,我正在创建一个简单的 gui 应用程序,其中包含两个按钮“选择文件”和“压缩文件”

我做了压缩功能所需的一切,现在我想要一些东西,当我点击“选择文件”时,会有一个类似于某些 FileManager 的弹出窗口,我选择 pdf 文件并将其路径存储为字符串以将其传递给压缩功能。

我希望一切都清楚

这是我的代码:

from kivy.config import Config
from PDFNetPython.PDFNetPython import PDFDoc, Optimizer, SDFDoc, PDFNet
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.core.window import Window
import os

Config.set('graphics', 'resizable', False)

s = """
MDScreen:
    md_bg_color : [250/255,34/255,83/255,1]
"""

c_file = """
MDRaisedButton:
    text: "Choose PDF"
    pos_hint : {"center_x": .5, "center_y": .6}
    size_hint : None,None
    on_press : app.choose_file()
    md_bg_color : 0,0,0,1
    width : 250
    font_size : 20 
"""

comp = """
MDRaisedButton:
    text : "Compress"
    pos_hint : {"center_x": .5, "center_y": .4}
    size_hint : None,None
    on_press : app.compress()
    md_bg_color : 0,0,0,1
    disabled : True
    width : 300
    font_size : 24.5
"""

class mainApp(MDApp):
    def get_size_format(n, b, factor=1024, suffix="B"):
        for unit in ["", "K", "M", "G", "T", "P", "E", "Z"]
            if b < factor : 
                return f"{b:.2f}{unit}{suffix}"
            b /= factor
        return f"{b:.2f}Y{suffix}"
    def compress(x, input: str, output = ""):
        if not output_file:
            output = input[:input.index(".")] + "_compressed" + ".pdf"
        initial_size = os.path.getsize(input)
        try: 
            PDFNet.Initialize()
            doc = PDFDoc(input)
            doc.InitSecurityHandler()
            Optimize.Optimize(doc)
            doc.Save(output,SDFDoc.e_linearized)
            doc.Close()
        except Exception as e:
            doc.Close()
            return False

        com.disabled = True

    def choose_file(x):
        print('Working good...')
        com.disabled = False

    Window.size = (270,300)
    def build(self):
        screen = Builder.load_string(s)
        
        global com,choose
        
        choose = Builder.load_string(c_file)
        com = Builder.load_string(comp)

        screen.add_widget(com)
        screen.add_widget(choose)

        return screen


if __name__ == "__main__":
    mainApp().run()

标签: python-3.xkivymd

解决方案


在 kv 文件中:

FileChooserIconView:
     id: file_choose
     on_selection : app.file_chooser(filechooser.selection)

在 py 文件中:

def file_chooser(x, filename):
     return filename[0]

推荐阅读