Я делаю программу на Python с графическим интерфейсом пользователя (GUI), используя Kivy.Эта программа имеет несколько вкладок, которые содержат 2 TextInput
виджетов в сочетании с кнопкой отправки.Чтобы не иметь по одной переменной на TextInput
на вкладку (что могло бы создать много переменных), я попытался присвоить все соответствующие TextInput
из разных вкладок одной и той же переменной kv, т.е. использовать одни и те же идентификаторы для всех TextInput
из разных вкладок,Содержимое переменных kv передается двум переменным Python ObjectProperty
.Все типы ввода одинаковы (т. Е. Строка).
При запуске программы и вводе данных на каждой вкладке, один за другим, входы на первой вкладке пусты (при выводе на Python), в то время каквходы второй вкладки работают должным образом.При удалении дублированных идентификаторов со второй вкладки в файле kv lang (т. Е. Повторное создание уникальных идентификаторов TextInput
первой вкладки) ввод первой вкладки фиксируется правильно.
Следовательно, повторениеодни и те же идентификаторы в одном и том же файле kv lang приводят к некорректному поведению захвата ввода.
Вот подмножество моего скрипта Python (максимально упрощено, чтобы подвести итог моей проблемы):
class MyLayout(BoxLayout):
# 2 inputs per tab
type_text_input = ObjectProperty() # 1st input
amount_text_input = ObjectProperty() # 2nd input
all_tab_content = [[] for i in range(9)]
regular_income_type = ObjectProperty() # combined input
def synchronizeTabContent(self, i):
# Give (back) the value corresponding to the current tab to the ListAdapter
self.regular_income_type.adapter.data = self.all_tab_content[i]
def submit(self, i):
# Get user inputs from the TextInputs
combined_input = self.type_text_input.text + ":" + self.amount_text_input.text
# Add string to the ListView and to the whole list
self.regular_income_type.adapter.data.extend([combined_input])
self.all_tab_content[i] = self.regular_income_type.adapter.data
# Reset the ListView
self.regular_income_type._trigger_reset_populate()
class SampleApp(App):
def build(self):
# Set the background color for the window
Window.clearcolor = (0.1, 0.1, 0.1, 1)
return MyLayout()
if __name__ == "__main__":
sample_app = SampleApp()
sample_app.run()
Вот подмножество моего скрипта kv lang:
<SubmitButton@Button>:
text: "Submit"
size_hint_x: 15
MyLayout:
<MyLayout>:
orientation: "vertical"
type_text_input: type_input # variable which is empty in first tab
amount_text_input: amount_input # variable which is empty in first tab
regular_income_type: students_list_view
padding: 10
spacing: 10
#### Some layout code was skipped here ####
BoxLayout:
orientation: "horizontal"
height: 30
BoxLayout:
orientation: "horizontal"
size_hint_x: .25
TabbedPanelItem:
text: "Regular"
on_press: root.synchronizeTabContent(4)
# ----- First tab -----
BoxLayout:
orientation: "vertical"
size_hint_x: 1
BoxLayout:
size_hint_x: 0.95
size_hint_y: 0.1
height: "40dp"
Label:
color: (0, 0, 0, 1)
text: "Type"
TextInput:
id: type_input # here is where is suspect the error comes from
Label:
color: (0, 0, 0, 1)
text: "Amount"
TextInput:
id: amount_input # here is where is suspect the error comes from
BoxLayout: # Button box
size_hint_y: 0.1
height: "40dp"
SubmitButton:
on_press: root.submit(4)
# ----- End of first tab -----
TabbedPanelItem:
text: "Deposit"
on_press: root.synchronizeTabContent(5)
# ----- Second tab -----
BoxLayout:
orientation: "vertical"
size_hint_x: 1
BoxLayout:
size_hint_x: 0.95
size_hint_y: 0.1
height: "40dp"
Label:
color: (0, 0, 0, 1)
text: "Type"
TextInput:
id: type_input # here is where is suspect the error comes from
Label:
color: (0, 0, 0, 1)
text: "Amount"
TextInput:
id: amount_input # here is where is suspect the error comes from
BoxLayout:
size_hint_y: 0.1
height: "40dp"
SubmitButton:
on_press: root.submit(5)
Переменные, которые хранят пустую строку для любого ввода первой вкладки, это self.type_text_input
и self.amount_text_input
.Соответствующие им kv-переменные type_input
и amount_input
, которые используются один раз для каждой вкладки и задаются как id
TextInput
.Я подозреваю, что повторное использование одних и тех же идентификаторов отвечает за мою проблему.
Есть ли способ сохранить входные данные различных TextInput
в одной и той же переменной Python, не используя разные переменные kv для каждой * 1028?*