kivy - 向kivy文件中的按钮添加功能
问题描述
我正在尝试将我的计算功能绑定到提交按钮。我是 Kivy 的新手,正在尝试进行一些练习。非常感谢任何学习技巧或窍门。这是我的代码:
蟒蛇文件:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
class MyGrid(Widget):
pass
class MyApp(App):
def build(self):
return MyGrid()
def calculations(self):
org_amount = float(self.ids.orgamount.text)
org_tip = int(self.ids.orgtip.text)
org_split = int(self.ids.split1.text)
tip1 = org_tip/100
tip = round(tip1 * org_amount, 2)
total = round(tip + org_amount, 2)
if org_split == 0:
split = org_split
else:
split = round(total/org_split,2)
if __name__ == "__main__":
MyApp().run()
基维文件:
<MyGrid>:
title: 'tipBot v1.0'
auto_dismiss: False
GridLayout:
cols:2
size: root.width * 0.8, root.height * 0.8
row_default_height: 30
row_force_default: True
center: root.width/2, root.height/2
Label:
text: "Enter orginal bill amount: "
TextInput:
id: orgamount
hint_text: 'Enter number w/ 2 decimal places'
hint_text_color: 'blue'
multiline:False
Label:
text: "How much tip will you leave: "
TextInput:
id: orgtip
hint_text: 'Enter whole number'
hint_text_color: 'blue'
multiline:False
Label:
text: "How many patrons will split the bill: "
TextInput:
id: split1
multiline: False
Label:
text: "Orignal Bill Amount: "
TextInput:
id: amount
multiline: False
Label:
text: "Amount of tip: "
TextInput:
id: tip
multiline: False
Label:
text: "Total with tip: "
TextInput:
id: withtip
multiline: False
Label:
text:"Amount for each patron split: "
TextInput:
id:patronsplit
multiline: False
Button:
id: Clear
text: "Clear"
size_hint_x: 0
on_release:
orgamount.text = ''
orgtip.text = ''
split1.text = ''
amount.text = ''
tip.text = ''
withtip.text = ''
patronsplit.text =''
Button:
id: Submit
text: "Submit"
size_hint_x:0.5
on_press: root.calculations()
enter code here
解决方案
问题是在你的kv
, 行:
on_press: root.calculations()
正在尝试调用规则calculations()
的根对象的方法kv
,即MyGrid
. 解决方法是将calculations()
方法移入MyGrid
:
class MyGrid(Widget):
def calculations(self):
org_amount = float(self.ids.orgamount.text)
org_tip = int(self.ids.orgtip.text)
org_split = int(self.ids.split1.text)
tip1 = org_tip / 100
tip = round(tip1 * org_amount, 2)
total = round(tip + org_amount, 2)
if org_split == 0:
split = org_split
else:
split = round(total / org_split, 2)
class MyApp(App):
def build(self):
return MyGrid()
推荐阅读
- database - 社交账户和普通账户数据库模型
- go - 使用给定的时间戳跟踪当前年份和月份
- android - 如何在 Room @Query 中使用 ROW_NUMBER()?
- vue.js - 如何仅从 Nuxt 的 buefy 导入导航栏、下拉菜单和模态框?
- javascript - 在 JavaScript 中使用默认参数,就像在 C# 中一样
- python - 在 PyCharm 中运行调试时设置 DJANGO_SETTINGS_MODULE 变量时出错
- javascript - 为什么这个函数不能同时隐藏 questionOne 和 questionTwo?
- react-native - React Native yarn run ios/android or npm run ios/android not working(无法从 Metro bundler 获取状态)
- pandas - 数据框:按数据时间索引和列分组
- google-analytics - 如何在 Google Analytics 中获取特定事件的用户信息?