0
我是Kivy的新手,我遇到了將項目添加到gridLayout的問題。這些項目是在我的python類中創建的,我想在我的kv文件中填充我的gridlayout。它可以工作,但標籤被添加到同一個地方(這意味着它們不在列中 - 它們都在一個單元格中)。我試過here的解決方案,但我仍然不知道什麼是錯的。如何動態地將用python代碼創建的小部件添加到kv文件
KV文件:
#:kivy 1.9.1
<Connected>:
BoxLayout:
orientation: 'vertical'
Label:
text: 'main window'
font_size: 32
BoxLayout:
orientation: 'vertical'
Label:
text: 'Flights'
font_size: 32
BoxLayout:
orientation: 'horizontal'
Label:
text: 'From'
font_size: 32
Label:
text: 'To'
font_size: 32
Label:
text: 'Company'
font_size: 32
Label:
text: 'Date'
font_size: 32
ScrollView:
size_hint_y: None
height: '200dp'
GridLayout:
id: flights_table
col: 4
size_hint_y: None
spacing: '1dp'
Button:
text: "Buy a ticket"
font_size: 32
on_press: root.order_flight()
Button:
text: "Logout"
font_size: 24
on_press: root.disconnect()
Python代碼:
# coding: utf-8
import json
import requests
from kivy.adapters.dictadapter import (
DictAdapter,
ListAdapter,
)
from kivy.properties import (
ListProperty,
ObjectProperty,
)
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.screenmanager import (
Screen,
SlideTransition,
)
from kivy.uix.listview import ListItemButton
class Connected(Screen):
u"""Screen after login in."""
flights = ListProperty()
def on_pre_enter(self, *args):
u"""Method that loads before the screen is loaded."""
self.flights = self.get_flights()
for flight in self.flights:
for value in [flight.get('from_city'), flight.get('to_city'), flight.get('company'), flight.get('flight_date')]:
self.ids.flights_table.add_widget(Label(text=value))
def disconnect(self):
u"""Logout method."""
self.manager.transition = SlideTransition(direction="right")
self.manager.current = 'login'
self.manager.get_screen('login').resetForm()
def get_flights(self):
u"""Method that gets the flights from a rest api."""
response = requests.get('http://127.0.0.1:8000/flights/', params={'format': 'json'})
if response.status_code == 200:
data = None
try:
data = json.loads(response.content.decode('utf-8'))
except ValueError as err:
raise
return data
return list()