You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Kivy框架调用Plyer导入文件时程序崩溃求助

解决方案

方案1:用Kivy内置FileChooser替代Plyer

Kivy自带的文件选择组件稳定性更强,无需依赖Plyer,直接实现图片导入:

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.popup import Popup

class ImageImporter(BoxLayout):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.orientation = 'vertical'
        self.select_btn = Button(text="导入图片")
        self.select_btn.bind(on_press=self.open_file_chooser)
        self.add_widget(self.select_btn)

    def open_file_chooser(self, instance):
        # 仅筛选常见图片格式
        file_chooser = FileChooserListView(filters=["*.png", "*.jpg", "*.jpeg", "*.gif"])
        popup = Popup(title="选择图片", content=file_chooser, size_hint=(0.9, 0.9))
        file_chooser.bind(on_submit=self.on_file_selected)
        popup.open()

    def on_file_selected(self, filechooser, selection, touch):
        if selection:
            selected_path = selection[0]
            # 在这里添加你的图片处理/加载逻辑
            print(f"已选中图片: {selected_path}")
            filechooser.parent.parent.dismiss()

class MyApp(App):
    def build(self):
        return ImageImporter()

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

方案2:修复Plyer使用并添加异常捕获

如果坚持用Plyer,必须补上完整异常处理,同时规范调用逻辑:

from plyer import filechooser
from kivy.app import App
from kivy.uix.button import Button

class MyApp(App):
    def build(self):
        btn = Button(text="导入图片")
        btn.bind(on_press=self.import_image)
        return btn

    def import_image(self, instance):
        try:
            # 指定仅选择图片文件
            result = filechooser.open_file(filters=["*.png", "*.jpg", "*.jpeg"])
            if result:
                selected_path = result[0]
                # 执行你的图片加载逻辑
                print(f"选中图片路径: {selected_path}")
        except Exception as e:
            # 捕获所有异常,避免程序崩溃
            print(f"导入出错: {str(e)}")

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

额外注意事项

  • 用PyInstaller打包时,需添加对应平台的隐藏导入,比如Windows平台要加--hidden-import plyer.platforms.win.filechooser,否则Plyer功能会失效。
  • 所有文件操作都要加异常捕获,覆盖文件不存在、权限不足、格式不支持等场景,彻底避免未处理异常导致崩溃。

内容的提问来源于stack exchange,提问作者Yoann Laubert

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 09:35:35