python-3.x - 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()
解决方案
在 kv 文件中:
FileChooserIconView:
id: file_choose
on_selection : app.file_chooser(filechooser.selection)
在 py 文件中:
def file_chooser(x, filename):
return filename[0]
推荐阅读
- python - 以编程方式为视频添加一个简单的暂停
- excel - 从公式中提取单元格地址
- windows - 已在组织中的客户端上卸载 SCCM
- firebase - Firebase 功能 + Firestore + 向多个令牌发送通知
- apache-spark - 无法在 spark sql 中注册 UDF
- python - 如何在 NLP 中使用 python 使用 .any() 或 a.all()?
- python - 将配对列表值转换为字典
- spring - 新创建/扩展的 JHipster 端点不起作用(404 错误)
- ruby-on-rails - Milia gem Rails 6
- c++ - 取消引用指针列表的迭代器