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

Kivy自拍应用报错:TypeError: 'NoneType' object is not callable 求助

解决Kivy Camera组件报错:TypeError: 'NoneType' object is not callable

错误根源

报错self._camera = CoreCamera(index=self.index, stopped=True) TypeError: 'NoneType' object is not callable,本质是Kivy找不到可用的摄像头后端实现,导致CoreCamera抽象类未被正确实例化(返回了None)。Kivy的Camera组件依赖平台特定的摄像头驱动库,默认环境下可能缺失对应依赖。

分步解决方案

1. 安装适配的摄像头后端依赖

先清理可能冲突的库,再安装Kivy官方推荐的摄像头依赖:

pip uninstall opencv-python pygame -y
pip install opencv-python-headless kivy[camera]
  • opencv-python-headless是无GUI的OpenCV版本,更适配Kivy的摄像头调用场景
  • kivy[camera]会自动安装对应平台的摄像头后端依赖(比如Linux的v4l2、Windows的dshow等)

2. 修正代码中的两处关键问题

你的代码存在摄像头索引和保存路径的潜在问题,修正后代码如下:

from kivy.app import App
from kivy.uix.camera import Camera
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
import os

class CameraExample(App):
    def build(self):
        layout = BoxLayout(orientation='vertical')
        
        # 尝试index=0(主摄像头)或index=1(副摄像头),根据设备调整
        self.cameraObject = Camera(play=False, index=0)
        # 先设置分辨率再启动摄像头,避免参数不生效
        self.cameraObject.resolution = (300, 300)
        self.cameraObject.play = True
        
        self.camaraClick = Button(text="Take Photo")
        self.camaraClick.size_hint = (.5, .2)
        self.camaraClick.pos_hint = {'x': .25, 'y': .75}
        self.camaraClick.bind(on_press=self.onCameraClick)
        
        layout.add_widget(self.cameraObject)
        layout.add_widget(self.camaraClick)
        return layout

    def onCameraClick(self, *args):
        # 自动创建保存目录,避免路径不存在报错
        save_dir = "kivyexamples"
        if not os.path.exists(save_dir):
            os.makedirs(save_dir)
        # 保存到当前工作目录的kivyexamples文件夹下
        self.cameraObject.export_to_png(f'{save_dir}/selfie.png')

if __name__ == '__main__':
    CameraExample().run()

3. 平台额外配置

  • Windows:检查摄像头权限是否开启,关闭其他占用摄像头的程序(如微信、Zoom)
  • Linux:安装v4l-utils工具,并将当前用户加入video组:
    sudo apt install v4l-utils
    sudo usermod -aG video $USER
    # 重启系统后生效
    
  • macOS:打开「系统设置-隐私与安全性-摄像头」,给运行该脚本的Python程序开启权限

内容的提问来源于stack exchange,提问作者Pol Arbiol i Rakuljic

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 12:57:25