Skip to main content
 首页 » 编程设计

Python/Kivy 属性错误

2024年10月24日10mate10pro

我正在编写一些代码以在 Python/Kivy 中为触摸屏创建 UI。我对两者都是新手,并且遇到了一些麻烦。我在 return PtWidg() 时出现了一个 AttributeError,但控制台没有给我任何 super 有用的信息:

Traceback (most recent call last): 
   File "/Users/revascharf/Documents/COLLEGE WORK/SENIOR YEAR/touchscreenInterface/touchUI.py", line 30, in <module> 
     ptApp().run() 
   File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/app.py", line 802, in run 
     root = self.build() 
   File "/Users/revascharf/Documents/COLLEGE WORK/SENIOR YEAR/touchscreenInterface/touchUI.py", line 26, in build 
     return PtWidg() 
   File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/uix/widget.py", line 320, in __init__ 
     Builder.apply(self, ignored_consts=self._kwargs_applied_init) 
   File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/lang.py", line 1970, in apply 
     self._apply_rule(widget, rule, rule, ignored_consts=ignored_consts) 
   File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/lang.py", line 2044, in _apply_rule 
     cls = Factory_get(cname) 
   File "/Applications/Kivy.app/Contents/Resources/kivy/kivy/factory.py", line 130, in __getattr__ 
     raise AttributeError 
 AttributeError 
 
Process finished with exit code 1 

这是我的 python 文件,touchUI.py:

import kivy 
import datetime 
 
from kivy.app import App 
from kivy.uix.widget import Widget 
from kivy.uix.button import Button 
 
kivy.require('1.9.0') 
from kivy.uix.image import Image 
 
 
class SendButton(Button): 
    def on_press(self): 
        now = datetime.datetime.now() 
        self.text = 'minute is ' + str(now.minute) 
 
 
class PtWidg(Widget): 
    pass 
 
 
class ptApp(App): 
    def build(self): 
        return PtWidg() 
 
 
if __name__ == '__main__': 
    ptApp().run() 

这是我的 .kv 文件的内容,pt.kv:

#kivy 1.9.0 
 
<sendButton>: 
    size: 40, 30 
    #pos: center_x + width / 4, center_y - height / 4 
 
 
<PtWidg>: 
 
    Image: 
        center_x: root.width / 4 
        top: root.top - 50 
        source: 'SensoryWalkLogo.png' 
        height: db(50) 
        width: db(50) 
 
    sendButton: 
        center_x: root.width - root.width / 4 
        top: root.top - 50 
        text: 'Send minute to MSP430' 
        font_size: 40 

真的,任何提示或技巧都会对我有很大帮助。谢谢!

请您参考如下方法:

您的代码有这些错误:

  1. 您在 kv 文件中编写了 sendButton 而不是 SendButton。
  2. 同样在 kv 文件中,您编写了 db(50) 而不是 dp(50)。使用字符串 '50dp' 也是一个有效选项。