我有两个文件demo.py
和demo.kv
。当运行demo.py
然后显示3行。因为我从数据库中获取数据。它显示为。
rows = [('test1', 'BAG1'), ('test2', 'BAG2'), ('test3', 'BAG3')]
for row in rows:
self.row_count += 1
self.add_widget(Row(button_text=str(self.row_count)))
所以迭代重复3次。我看起来像
[![在此处输入图像说明] [1]] [1]
现在我想在TextBox中显示值,如
Number name value
1. test1 BAG1
2. test2 BAG2
3. test3 BAG3
有人可以帮助我如何在另一个类(root.col_data[3]
)的for循环中传递值root.col_data[4]
和class Rows(BoxLayout):
吗?
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ListProperty, StringProperty
Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (500, 400)
class User(Screen):
def add_more(self):
self.ids.rows.add_row()
class Row(BoxLayout):
col_data = ListProperty(["?", "?", "?", "?", "?"])
button_text = StringProperty("")
def __init__(self, **kwargs):
super(Row, self).__init__(**kwargs)
#self.mode = obj.mode
self.col_data[0] = ''
self.col_data[1] = ''
self.col_data[2] = ''
self.col_data[3] = ''
self.col_data[4] = ''
class Rows(BoxLayout):
row_count = 0
def __init__(self, **kwargs):
super(Rows, self).__init__(**kwargs)
self.add_row()
def add_row(self):
#fetching from database
rows = [('test1', 'BAG1'), ('test2', 'BAG2'), ('test3', 'BAG3')]
for row in rows:
Row().col_data[3] = row[0]
Row().col_data[4] = row[1]
self.row_count += 1
self.add_widget(Row(button_text=str(self.row_count)))
class Test(App):
def build(self):
self.root = Builder.load_file('demo.kv')
return self.root
if __name__ == '__main__':
Test().run()
<Row>:
size_hint_y: None
height: self.minimum_height
height: 40
Button:
text: root.button_text
size_hint_x: None
top: 200
TextInput:
text: root.col_data[3]
width: 300
TextInput:
text: root.col_data[4]
width: 300
<Rows>:
size_hint_y: None
height: self.minimum_height
orientation: "vertical"
User:
BoxLayout:
orientation: "vertical"
padding : 20, 5
BoxLayout:
orientation: "horizontal"
#padding : 10, 10
spacing: 10, 10
size: 450, 40
size_hint: None, None
Label:
size_hint_x: .2
text: "Number"
text_size: self.size
valign: 'bottom'
halign: 'center'
Label:
size_hint_x: .4
text: "name"
text_size: self.size
valign: 'bottom'
halign: 'center'
Label:
size_hint_x: .4
text: "Value"
text_size: self.size
valign: 'bottom'
halign: 'center'
ScrollView:
Rows:
id: rows
BoxLayout:
orientation: "horizontal"
size_hint_x: .2
size_hint_y: .2
Button:
text: "+Add More"
on_press: root.add_more()
答案 0 :(得分:1)
Row().col_data[3] = row[0]
Row().col_data[4] = row[1]
当您编写Row()
时,您创建了Row的新实例。您想要创建一次并修改它。
像这样更改add_row
功能:
def add_row(self):
#fetching from database
rows = [('test1', 'BAG1'), ('test2', 'BAG2'), ('test3', 'BAG3')]
for row in rows:
self.row_count += 1
r = Row(button_text=str(self.row_count))
r.col_data[3] = row[0]
r.col_data[4] = row[1]
self.add_widget(r)
结果: