Kivy:如何正确操作 KV lang 中定义的 python 中的小部件
Kivy: How to correctly manipulate a widget in python that is defined in KV lang
我有以下用 KV lang 写的:
TextInput:
id: user_input_temp
font_size: 50
size_hint_y: None
input_filter: 'float'
multiline: False
Label:
text: "Celsius"
Label:
id: celsius
text: root.temp_conv()
我尝试在 python 代码中使用 user_input_temp
:
class Temperature(Screen,BoxLayout):
def temp_conv(self):
number = self.ids.user_input_temp.text
input = float(number)
celsius = (input - 32)*(5/9)
self.ids.celsius.text = str(celsius)
但是我收到一个错误 - ValueError: could not convert string to float:
如何正确转换小部件的 .text
? (最好使用小部件 ID)
检查它无法转换的值。在您的示例中,您实际上并没有设置文本,所以它可能正在执行 float('')
,这会给出您看到的错误,因为 ''
没有描述浮点数。在那种情况下,您会想尝试进行转换,但是 return 一些合适的东西或者如果失败则什么也不做。
我有以下用 KV lang 写的:
TextInput:
id: user_input_temp
font_size: 50
size_hint_y: None
input_filter: 'float'
multiline: False
Label:
text: "Celsius"
Label:
id: celsius
text: root.temp_conv()
我尝试在 python 代码中使用 user_input_temp
:
class Temperature(Screen,BoxLayout):
def temp_conv(self):
number = self.ids.user_input_temp.text
input = float(number)
celsius = (input - 32)*(5/9)
self.ids.celsius.text = str(celsius)
但是我收到一个错误 - ValueError: could not convert string to float:
如何正确转换小部件的 .text
? (最好使用小部件 ID)
检查它无法转换的值。在您的示例中,您实际上并没有设置文本,所以它可能正在执行 float('')
,这会给出您看到的错误,因为 ''
没有描述浮点数。在那种情况下,您会想尝试进行转换,但是 return 一些合适的东西或者如果失败则什么也不做。