运行Kivy相机示例遇AttributeError:'CameraOpenCV'无'fps'属性
Hey there, let's break down and fix this frustrating error you're hitting when running Kivy's official camera example. I've dealt with this exact issue back when Kivy 1.10.0 was still widely used, so here's what's going on and how to fix it:
What's Causing the Error?
In Kivy 1.10.0, the CameraOpenCV backend (which might be your default camera provider) doesn't expose an fps attribute. But the official camera example code assumes all camera providers have this property, hence the AttributeError when it tries to access it.
Solutions to Try
1. Upgrade Kivy to a Newer Version (Recommended)
This is the cleanest fix—later Kivy versions (1.11.0 and above) added the fps attribute to CameraOpenCV specifically to resolve this issue. Run this command to upgrade:
pip install --upgrade kivy
Once upgraded, re-run your main.py and the error should vanish.
2. Force a Different Camera Provider
If upgrading isn't an option right now, you can tell Kivy to use a different camera backend that supports the fps attribute. Two reliable options are pygame or sdl2:
Option A: Set the Provider in Your Code
Add these lines at the very top of your main.py:
from kivy.config import Config # Use pygame as the camera provider Config.set('graphics', 'camera', 'pygame')
Just make sure you have pygame installed first:
pip install pygame
Option B: Specify the Provider via Command Line
Run your app with this command instead:
python3 main.py -c graphics:camera=pygame
Or use sdl2 if you prefer that backend (it's often pre-installed with Kivy):
python3 main.py -c graphics:camera=sdl2
3. Add a Fallback for the fps Attribute
If you need to keep using CameraOpenCV and can't upgrade Kivy, modify your example code to handle the missing attribute. Look for where the code accesses camera.fps and replace it with a check:
# Replace lines like this: # fps_label.text = f"FPS: {self.camera.fps}" # With this fallback: if hasattr(self.camera, 'fps'): current_fps = self.camera.fps else: current_fps = 30 # Use a reasonable default value fps_label.text = f"FPS: {current_fps}"
This way, the code won't crash even if the provider lacks the fps attribute.
内容的提问来源于stack exchange,提问作者Blind0ne

