Kivy按钮点击清空TextField报错:'super'对象无'getattr'属性
错误原因及修复步骤
1. MDLabel语法错误
kv代码中MDLabel:your text`属于无效语法,直接删除多余的your text部分,改为:
MDLabel:
2. TextField的id格式错误
Kivy中组件id不需要用引号包裹,修改两个TextField的id:
id: t1 # 移除原有双引号
id: t2 # 移除原有双引号
3. on_release事件赋值符号错误
按钮点击事件中使用冒号:赋值是错误的,Kivy语言中赋值需用等号=,修改为:
on_release: root.ids.t1.text = "" root.ids.t2.text = ""
4. rgba颜色值范围错误
Kivy中rgba()函数参数需为0-1之间的浮点数,不能用0-255的整数,需将数值除以255:
- MDLabel的color:
color: 135/255, 133/255, 193/255, 1 - TextField的foreground_color、cursor_color:
foreground_color: 0/255, 0/255, 59/255, 1 - Button画布中的Color:
rgb: 52/255, 0/255, 231/255(rgb模式无需alpha值)
修复后的完整studentregister.kv代码
MDScreen: name: "student_create" MDFloatLayout: md_bg_color: 1,1,1,1 MDIconButton: icon: "arrow-left" pos_hint: {"center_y": .95} on_release: root.manager.transition.direction= "right" root.manager.current= "newaccount" Image: source: "images/newstud.png" pos_hint: {"center_x": .78, "center_y": .9} size_hint: .13, .13 MDLabel: text: 'Create New Student Account' font_size: "18sp" pos_hint: {"center_x": .6, "center_y": .84} color: 135/255, 133/255, 193/255, 1 MDFloatLayout: size_hint: .7, .07 pos_hint: {"center_x": .5, "center_y": .73} MDTextField: id: t1 hint_text: 'Calling Name' pos_hint: {'center_x': 0.43, 'center_y': 0.43} background_color: 1,1,1,0 foreground_color: 0/255, 0/255, 59/255, 1 cursor_color: 0/255, 0/255, 59/255, 1 font_size: '12sp' cursor_width: '2sp' multiline: False MDFloatLayout: size_hint: .7, .07 pos_hint: {"center_x": .5, "center_y": .65} MDTextField: id: t2 hint_text: 'Surname' pos_hint: {'center_x': 0.43, 'center_y': 0.43} background_color: 1,1,1,0 foreground_color: 0/255, 0/255, 59/255, 1 cursor_color: 0/255, 0/255, 59/255, 1 font_size: '12sp' cursor_width: '2sp' multiline: False Button: text: "Clear" size_hint: .35, .065 background_color: 0,0,0,0 pos_hint: {"center_x": .32, "center_y": .06} on_release: root.ids.t1.text = "" root.ids.t2.text = "" canvas.before: Color: rgb: 52/255, 0/255, 231/255 RoundedRectangle: size: self.size pos: self.pos radius: [5]
额外提示
- 建议使用KivyMD提供的
MDButton替代普通Button,风格更统一 - 确保图片路径
images/newstud.png存在,否则会加载失败
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

