【问题标题】:how do I select directories and files in KivyMD如何在 KivyMD 中选择目录和文件
【发布时间】:2021-12-08 15:05:36
【问题描述】:

我正在尝试通过我使用file manager 制作的一个简单应用程序选择一个文件(图片),但每当我单击按钮访问文件(即打开目录)。我不知道想要是错的,我什至不知道我做错了什么。

如果有任何帮助,我将不胜感激。

这是我的 .py 文件

from kivy.factory import Factory
from kivy.uix.modalview import ModalView

from kivymd.uix.filemanager import MDFileManager
from kivymd.theming import ThemeManager
from kivymd.toast import toast


from kivymd.app import MDApp
from kivy.core.window import Window


Window.size = (300, 530)


class MainApp(MDApp):
    title = "File Manage"

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        Window.bind(on_keyboard=self.events)
        self.manager_open = False
        self.manager = None

    def build(self):
        self.theme_cls.primary_palette = 'Gray'
        self.theme_cls.primary_hue = '200'
        self.theme_cls.theme_style = 'Dark'

        return Factory.ExampleFileManager()

    def file_manager_open(self):
        if not self.manager:
            self.manager = ModalView(size_hint=(1, 1), auto_dismiss=False)
            self.file_manager = MDFileManager(
                exit_manager=self.exit_manager, select_path=self.select_path)
            self.manager.add_widget(self.file_manager)
            self.file_manager.show('/')  # output manager to the screen
        self.manager_open = True
        self.manager.open()

    def select_path(self, path):
        '''It will be called when you click on the file name
        or the catalog selection button.

        :type path: str;
        :param path: path to the selected directory or file;
        '''

        self.exit_manager()
        toast(path)

    def exit_manager(self, *args):
        '''Called when the user reaches the root of the directory tree.'''

        self.manager.dismiss()
        self.manager_open = False

    def events(self, instance, keyboard, keycode, text, modifiers):
        '''Called when buttons are pressed on the mobile device..'''

        if keyboard in (1001, 27):
            if self.manager_open:
                self.file_manager.back()
        return True


if __name__ == "__main__":
    app = MainApp()
    app.run()

这是我的 .kv 文件:

<ExampleFileManager@BoxLayout>
    orientation: 'vertical'

    MDToolbar:
        id: progress_toolbar
        title: 'Progress'

    ScrollView:
        MDGridLayout:
            cols: 2
            adaptive_height: True
            spacing: (10, 15)
            padding: [25, 25]

            MDLabel:
                halign: 'center'
                text: 'Before'

            MDLabel:
                halign: 'center'
                text: 'Now'

            MDCard:
                ripple_behavior: True
                orientation: 'vertical'
                size_hint_y: None
                size: 120, 220
                elevation: 15
                radius: 8
                MDIconButton:
                    icon: "camera-outline"
                    user_font_size: "64sp"
                    pos_hint: {"center_x": .5, "center_y": .5}
                    on_release: app.file_manager_open()

            MDCard:
                ripple_behavior: True
                orientation: 'vertical'
                size_hint_y: None
                size: 120, 220
                elevation: 15
                radius: 8
                MDIconButton:
                    icon: "camera-outline"
                    user_font_size: "64sp"
                    pos_hint: {"center_x": .5, "center_y": .5}
                    on_release: app.file_manager_open()


            MDTextField:
                hint_text: 'Date'
                width: 100

            MDTextField:
                hint_text: 'Date'
                width: 100

            MDTextField:
                hint_text: 'Weight'
                width: 80

            MDTextField:
                hint_text: 'Weight'
                width: 80

编辑: 新代码:

from kivy.lang import Builder
from kivymd.app import MDApp
from kivy.core.window import Window
from plyer import filechooser

Window.size = (300, 530)

KV = """
MDBoxLayout:
    orientation: 'vertical'

    MDToolbar:
        id: progress_toolbar
        title: 'Progress'

    ScrollView:
        MDGridLayout:
            cols: 2
            adaptive_height: True
            spacing: (10, 15)
            padding: [25, 25]

            MDLabel:
                halign: 'center'
                text: 'Before'

            MDLabel:
                halign: 'center'
                text: 'Now'

            MDCard:
                ripple_behavior: True
                orientation: 'vertical'
                size_hint_y: None
                size: 120, 220
                elevation: 15
                radius: 8
                MDIconButton:
                    icon: "camera-outline"
                    user_font_size: "24sp"
                    pos_hint: {"center_x": .5, "center_y": .5}
                    on_release: app.file_chooser1()
                Image:
                    id: img1
                    allow_stretch: True
                    keep_ratio: False
                    # size_hint_y: .5

            MDCard:
                ripple_behavior: True
                orientation: 'vertical'
                size_hint_y: None
                size: 120, 220
                elevation: 15
                radius: 8
                MDIconButton:
                    icon: "camera-outline"
                    user_font_size: "24sp"
                    pos_hint: {"center_x": .5, "center_y": .5}
                    on_release: app.file_chooser2()
                Image:
                    id: img2
                    allow_stretch: True
                    keep_ratio: False
                    # size_hint_y: .5


            MDTextField:
                hint_text: 'Date'
                width: 100

            MDTextField:
                hint_text: 'Date'
                width: 100

"""


class Example(MDApp):

    def build(self):
        return Builder.load_string(KV)

    def file_chooser1(self):
        filechooser.open_file(on_selection=self.selected1)

    def file_chooser2(self):
        filechooser.open_file(on_selection=self.selected2)

    def selected1(self, selection1):
        self.root.ids.img1.source = selection1[0]

    def selected2(self, selection2):
        self.root.ids.img2.source = selection2[0]


Example().run()

【问题讨论】:

    标签: python python-3.x kivy kivy-language kivymd


    【解决方案1】:

    除了使用FileManager 小部件,实际上还有一个更好的替代方法,它来自plyer module,特别是filechooser API。它的作用是打开设备的默认文件管理器应用程序以选择文件夹、文件或保存文件。这是一个例子:

    def file_manager_open(self):
        from plyer import filechooser
        path = filechooser.open_file()[0] 
        # this method returns a list with the first index
        # being the path of the file selected
        toast(path)
    

    有关此库的 API 的更多信息here

    我可以给你的一个提示是,因为这个文件选择器在 Windows 平台上非常弱,如果你愿意,我建议使用tkinterfiledialog

    【讨论】:

    • 非常感谢@weebify,这实际上解决了问题。但是在我选择图像后,图像没有出现在屏幕上..请问我做错了什么
    • 我相信这是因为您的select_path 方法在选择您想要的图像后没有被调用,因此没有显示图像。我已经编辑了我的答案,所以它应该会显示出来,检查一下
    • 感谢@Weebify,但这实际上并没有显示图像,虽然它显示了路径,但我的目标是在“MDCard”上显示图像。非常感谢您的帮助,非常感谢..
    • 非常感谢您的帮助。我能够找到一个关于 plyer 的视频,并且我在代码中更改了很多东西。我在上一篇文章中添加了新代码。图像现在显示,但我现在有两个新问题,1.图像的方向在输入时会发生变化,我希望在输入时方向保持不变。 2. 我想让输入的图像文件在再次打开时可用,所以我需要保存输入的图像文件。请问我如何使这些事情发生。非常感谢您的帮助,我真的很感激。
    • 我真的不知道该怎么做才能使您的第一个请求成功,但第二个请求:只需在某处创建一个保存文件夹,例如您的主目录(您可以通过使用plyer.storagepath.get_home_dir()),然后将您的输入图像保存在那里。之后,只需检查是否有任何图像文件(可以根据您的喜好命名,以防有人弄乱文件夹),如果 True 然后再次打开图像时,它可用。可能不是最优化的方式,但至少是最简单的方式
    猜你喜欢
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 1970-01-01
    • 2020-08-01
    • 2016-03-17
    • 2021-04-30
    • 2012-09-20
    • 1970-01-01
    相关资源
    最近更新 更多