python - 从 .kv 类获取值到 .py 函数
问题描述
我在 main.kv 文件中有自定义类,通过命令我可以添加到 createRecipe.kv 文件中的另一个屏幕。但是如何将 names.text(来自标签)、unit.text(来自标签)和 qtyRe.text(来自 TextInput)读取到 main.py 文件?
screen_manager.get_screen('createRecipe').ingredientforRecipe.add_widget(AddIngToRecipe(names=names, unit=unit))
主文件
<AddIngToRecipe>
id: addIngToRecipe
names: names
unit: unit
MDLabel:
id: names
text: str(root.names)
markup: True
font_size: '20sp'
size_hint_x: .8
pos_hint: {"center_x": .4, "center_y": .4}
MDLabel:
id: unit
text: str(root.unit)
markup: True
font_size: '18sp'
size_hint_x: .8
theme_text_color: "Custom"
text_color: 1, 1, 1, 1
pos_hint: {"center_x": .73, "center_y": .4}
TextInput:
id: qtyRe
hint_text: 'Qty:'
size_hint: 1, None
input_filter: 'int'
pos_hint: {"center_x": .5, "center_y": .5}
height: 55
cursor_color: 75/255, 0/255, 130/255, 1
background_color: 0, 0, 0, 0
multiline: False
创建食谱.kv
MDScreen:
name: 'createRecipe'
ingredientforRecipe: ingredientforRecipe
MDFloatLayout:
id: create_recipe
ScrollView:
do_scroll_y: True
do_scroll_x: False
size_hint_y: .41
pos_hint: {"center_x": .55, "y": 0.41}
bar_width: 0
GridLayout:
id: ingredientforRecipe
cols: 1
height: self.minimum_height
row_default_height: 70
size_hint_y: None
主文件
class AddIngToRecipe(FakeRectangularElevationBehavior, FloatLayout, TouchBehavior):
names = ObjectProperty()
unit = ObjectProperty()
def get_from(self):
names1 = self.ids.qtyRe.text
print(names1)
class PieceofCake(MDApp, Screen):
def create_recipe(self, Renames, Recomment):
self.get_from_addIngToRecipe = AddIngToRecipe()
self.get_from_addIngToRecipe.get_from()
names = self.ids.ingredientforRecipe.qtyRe.text
print(names)
print(Renames)
print(Recomment)
解决方案
names = self.ids.names.text
unit = self.ids.unit.text
qtyRe = self.ids.qtyRe.text
此外,如果您想从与您正在使用的类不同的类中访问小部件的值,您可以使用:
MDApp.get_running_app().root.ids.idOfTheClass.ids.idOfTheWidget.valueToGet
MDApp.get_running_app().root.ids.idOfTheClass
作用与self
目标类相同
推荐阅读
- quarkus - 无法启动新生成的项目
- flutter - Flutter 安全路由与 Flutter-fire 身份验证保护并避免不必要的重建
- javascript - 在 textarea 中显示带有适当格式的文本(例如
) - python - 如何检查是否只有一个 argparse 参数存在
- autohotkey - 我在 AHK 中的 GetKeyState 遇到问题
- c++ - 为什么编译器会报这样的错误?('width' is not declared in this scope)
- c# - 为什么我的 ModelState.AddModelError 会在 await HttpClient.PostAsync() 之前工作,但之后不行?
- c++ - C++ 向量内存分配
- python - 如何解决错误“无效的默认值
“在 django 中 - shell - 如何在 cron 选项卡中设置环境变量并在 shell 脚本中获取这些值