【发布时间】:2020-12-06 18:40:37
【问题描述】:
我使用了 KivyMD 文档中有关“动态选项卡管理”的代码,因此用户可以添加/删除选项卡。但是,创建的每个选项卡显然都是相同的,因此我放入其中的小部件也是如此。这意味着,如果我尝试从 例如 Tab 3 获取所述小部件的 id,则没有办法这样做,因为它与 相同的 id 例如 Tab 1 中的小部件。代码如下:
.py 文件
def on_start(self):
self.add_tab()
def get_tab_list(self):
print(self.root.ids.addworkouts.ids.tabs.get_tab_list())
def add_tab(self):
self.index += 1
self.root.ids.addworkouts.ids.tabs.add_widget(Tab(text=f"Exercise {self.index}"))
def remove_tab(self):
self.index -= 1
self.root.ids.addworkouts.ids.tabs.remove_widget(
self.root.ids.addworkouts.ids.tabs.get_tab_list()[0]
)
.kv 文件
<AddWorkouts>
name: 'AddWorkouts'
tabs: tabs
BoxLayout:
orientation: 'vertical'
MDToolbar:
title: ' '#app.getWorkoutName()
type: 'top'
left_action_items: [['keyboard-backspace', lambda x: app.goBacktoMyWorkouts()]]
#md_bg_color: app.theme_cls.accent_color
elevation: 10
FloatLayout:
canvas:
Color:
rgba: 0, 0, 0.5, 0.9
Rectangle:
pos: self.pos
size: self.size
MDTabs:
id: tabs
FloatLayout:
canvas:
Color:
rgba: 1, 1, 1, 1
Rectangle:
size: self.size
pos: self.pos
pos_hint: {'center_x': 0.5, 'y': 0.1}
size_hint: 0.8, 0.6
MDTextField:
pos_hint: {'x': 0.05, 'y': 0.8}
size_hint: 0.6, None
hint_text: 'Exercise Name'
helper_text_mode: 'on_focus'
required: 'True'
multiline: False
<Tab>
MDList:
MDBoxLayout:
adaptive_height: True
md_bg_color: 1, 1, 1, 1
MDFlatButton:
text: "ADD EXERCISE"
text_color: 16/255, 167/255, 249/255, 1
on_release: app.add_tab()
MDFlatButton:
text: "REMOVE LAST EXERCISE"
text_color: 16/255, 167/255, 249/255, 1
on_release: app.remove_tab()
Tab 1,其中 MDTextField 中的输入为“Hi”:
Tab2,其中 MDTextField 中的输入与 Tab 重复:
是否仍然让用户能够添加和删除选项卡,但是让所有小部件(如 .kv 文件中的 MDTextField )具有不同的 ID,以便我可以访问用户输入从他们?提前谢谢你,如果这个问题的措辞不好,请询问更多信息!
【问题讨论】: