Today I added a section to my code where the user can save their gardens. The new garden’s information goes to a database using SQLAlchemy. I also made it so the list of gardens can be viewed using RecycleView on the main page. The idea is that users can have as many gardens as they would like and they will be able to tap on each garden name to see the specific information. Below is a screenshot and the code for the homepage.
I have three files: .kv, main.py, and homepage.py. This keeps main.py free as I continue to add screens.
main.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.core.window import Window
from homescreen import HomePageScreen
Builder.load_file("design.kv")
Window.clearcolor = (0, 0.6, 0.1, 1.0)
Window.size = (400, 600)
class HomeScreen(HomePageScreen):
pass
class RootWidget(ScreenManager):
pass
class MainApp(App):
def build(self):
self.title = "My Gardens App"
return RootWidget()
if __name__ == "__main__":
MainApp().run()
homescreen.py. Most of this is the sqlalchemy code.
from kivy.uix.screenmanager import Screen
from sqlalchemy import MetaData, create_engine, Table, Column, Integer, String
class HomePageScreen(Screen):
def current_gardens_data(self):
meta = MetaData()
engine = create_engine("sqlite:///gardens_app_new.db", echo=True)
conn = engine.connect()
gardens = Table(
"gardens", meta,
Column("id", Integer, primary_key=True),
Column("name", String),
Column("notes", String),
)
info = gardens.select()
return conn.execute(info).fetchall()# -- Formatting the Recycleview -- #
def all_gardens(self):
records = []
for garden in self.current_gardens_data():
record = {"font_size": "20sp", "text": f"{garden[1]}",}
records.append(record)
return [x for x in records]
design.kv
<Button>:
font_size: 20
color: 1, 1, 1, 1
background_color: 0, 1, 0, 1
<RecycleButton@Button>:
font_size: 20
color: 1, 1, 1, 1
background_color: 0, 0, 1, 0.3
<TextInput>:
font_size: 20
<HomeScreen>:
GridLayout:
cols: 1
GridLayout:
cols: 1
padding: 15, 15
Label:
text: "My Gardens"
size_hint: 0.2, 0.2
font_size: "30sp"
GridLayout:
cols: 2
size_hint: 0.3, 0.3
Button:
text: "View Plants"
on_press:
root.manager.transition.direction = "left"
root.manager.current = "search_plants_screen"
size_hint: 0.3, 0.3
Button:
text: "Add a Plant"
on_press:
root.manager.transition.direction = "left"
root.manager.current = "add_plant_screen"
size_hint: 0.3, 0.3
Label:
text: "All Gardens:"
size_hint: 0.2, 0.2
font_size: 20
RecycleView:
id: current_gardens
data: root.all_gardens()
viewclass: "RecycleButton"
RecycleBoxLayout:
default_size: None, dp(60)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
Label:
size_hint: 0.1, 0.1
Button:
id: garden1
text: "Add a Garden"
size_hint: 0.3, 0.3
on_press: root.manager.current = "add_garden_screen"<RootWidget>:
HomeScreen:
name: "home_screen"