如何从for循环获取用户输入的数据到kivymd中的python文件 [英] how to get data of user input from a for loop to python file in kivymd
问题描述
我正在制作一个将2个矩阵相乘的应用程序.为此,我创建了用户界面,但无法弄清楚如何在python文件中获取用户输入,因此我可以在那里进行操作.
i am making an app to multiply 2 matrix. for that i created the user interface but cant figure it out how to get the user input in my python file, so i can do operations there.
这是我的奇异果文件
#: import MDTextField kivymd.uix.textfield.MDTextField
<MyApp>:
NavigationLayout:
ScreenManager:
Screen:
name: "screen1"
GridLayout:
cols: 4
padding: 30
spacing: 20
size: root.width * 0.4, root.height * 0.8
row_force_default: True
row_default_height: 30
pos_hint: {'center_x': 0.5,'center_y':0.55}
size_hint: (None, None)
size: self.minimum_size
top: self.height
on_parent:
for i in range(16): self.add_widget(MDTextField(hint_text= 'sc', helper_text= 'hello', size_hint_x= None, width = 40))
MDRectangleFlatButton:
text: 'back'
pos_hint: {'center_x': 0.5, 'center_y': 0.4}
on_release:
app.find_multiply()
因为我的MDTextField位于for循环内,所以我不能在那里使用id,因为从那里我将获得具有相同id的所有16个文本字段. 我如何在我的python文件中的app.find_multiply函数中获取全部16个文本字段输入,以便可以在那里执行操作.
since my MDTextField is inside a for loop, so i can't use an id there because from that i will get all 16 text field with the same id. how do i get my all 16 textfield input inside the app.find_multiply funcition in my python file, so i can perform operation there.
推荐答案
存储对文本字段的引用,并在以后访问它们以执行所需的操作.
Store references to your text fields, and access them later to do what you want.
我将删除您的on_parent
,将GridLayout
替换为您自己的类MyGridLayout(GridLayout):
,并让该类执行以下操作:
I would delete your on_parent
, replace the GridLayout
with your own class MyGridLayout(GridLayout):
, and have that class do:
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.text_fields = [MdTextField(hint_text= 'sc', helper_text= 'hello', size_hint_x= None, width = 40))] for _ in range(16)]
然后,当您要访问它们时,可以通过例如entered_numbers = [int(field.text) for field in self.text_field]
.
Then later when you want to access them, you can iterate through e.g. entered_numbers = [int(field.text) for field in self.text_field]
.
当然,这只是一个基本示例,实际上,您需要进行错误检查等.
Of course that's just a basic example, in reality you'll want error checking etc.
这篇关于如何从for循环获取用户输入的数据到kivymd中的python文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!