Listing Order Numbers, Items and Subitems from database - python

So, I'm trying to create a list that pulls from a mysql database that displays an order # as a button and a new window expands to display the order numbers items/subitems with checkboxes to have checked when an item is selected. I have the window to pop up; however, nothing populates and my query prints out information/list. After all boxes are checked and a Finish button is clicked on, it will remove the order from the list to show it has been worked on. I found this on the forums; however, it's not pulling anything for me:
How to fetch data from database and show in table in kivy+python
Thank you!
main.py
import pymysql
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
orderNum = "1"
class TextInputPopup(Popup):
obj = ObjectProperty(None)
obj_text = StringProperty("")
def __init__(self, obj, **kwargs):
super(TextInputPopup, self).__init__(**kwargs)
self.obj = obj
self.obj_text = obj.text
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
def on_press(self):
popup = TextInputPopup(self)
popup.open()
def update_changes(self, txt):
self.text = txt
class RV(BoxLayout):
data_items = ListProperty([])
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_order()
def get_order(self):
connection = pymysql.connect(host='localhost', user='root',passwd='password', db='Shop')
cursor = connection.cursor()
cursor.execute("SELECT itemName, ITEM FROM order_list WHERE orderID=%s", (orderNum,))
rows = cursor.fetchall()
# create data_items
for row in rows:
for col in row:
self.data_items.append(col)
class TestApp(App):
title = "Kivy RecycleView & pymysql Demo"
def build(self):
return RV()
if __name__ == "__main__":
TestApp().run()
kivy.kv
#:kivy 1.10.0
<TextInputPopup>:
title: "Popup"
size_hint: None, None
size: 400, 400
auto_dismiss: False
BoxLayout:
orientation: "vertical"
TextInput:
id: txtinput
text: root.obj_text
Button:
size_hint: 1, 0.2
text: "Finish"
on_release:
root.obj.update_changes(txtinput.text)
root.dismiss()
Button:
size_hint: 1, 0.2
text: "Cancel Changes"
on_release: root.dismiss()
<SelectableButton>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
<RV>:
BoxLayout:
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 2
Label:
text: "Order Number"
BoxLayout:
RecycleView:
viewclass: 'SelectableButton'
data: [{'text': str(x)} for x in root.data_items]
SelectableRecycleGridLayout:
cols: 2
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
Here's my list that pulls information and uses a print function:
('Sub', 'Italian')
('Sub', 'Meatball')
('Drink', 'Apple Juice')
('Side', 'Salad')
('Soup', 'Chicken and rice')
What I have and What I'm Trying to Achieve

Related

Display List of Ordereddict in Kivy

I have a list of Ordereddict as follows
list1= [OrderedDict([('Numbers', '15'), ('FirstName', 'John'), ('SecondName', 'Raul'), ('MiddleName', 'Kyle'), ('Grade', 22)]),
OrderedDict([('Names', 'John'), ('NewFirstName', 'Mark'), ('NewSecondName', 'Sachel'), ('NewThirdName', 'Raul'), ('Grade', 15)]),
OrderedDict([('Numbers', '25'), ('FirstName', 'Kyle'), ('SecondName', 'Venn'), ('MiddleName', 'Marcus'), ('Grade', 24)]),
OrderedDict([('Names', 'Sachel'), ('NewFirstName', 'Venn'), ('NewSecondName', 'Kyle'), ('NewThirdName', 'John'), ('Grade', 71)])]
There are 8 unique keys and one common key in it, i would like to create a table from it in kivy with the same order, with keys being the header of the table. My expected output is as below, i am new to kivy ecosystem and i dont see anything like tableview in that, any other views could be used to get this output and how
Expected output in kivy
I took the simpler recycyle view example given in the comment and edited the no of columns to 9 and tried picking the values from Ordereddict and i got the below output, since i am new to kivy i am not sure to pull the values as in expected output
Below are .py and .kv files
check.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from collections import OrderedDict
list1= [OrderedDict([('Numbers', '15'), ('FirstName', 'John'), ('SecondName', 'Raul'), ('MiddleName', 'Kyle'), ('Grade', 22)]),
OrderedDict([('Names', 'John'), ('NewFirstName', 'Mark'), ('NewSecondName', 'Sachel'), ('NewThirdName', 'Raul'), ('Grade', 15)]),
OrderedDict([('Numbers', '25'), ('FirstName', 'Kyle'), ('SecondName', 'Venn'), ('MiddleName', 'Marcus'), ('Grade', 24)]),
OrderedDict([('Names', 'Sachel'), ('NewFirstName', 'Venn'), ('NewSecondName', 'Kyle'), ('NewThirdName', 'John'), ('Grade', 71)])]
class TextInputPopup(Popup):
obj = ObjectProperty(None)
obj_text = StringProperty("")
def __init__(self, obj, **kwargs):
super(TextInputPopup, self).__init__(**kwargs)
self.obj = obj
self.obj_text = obj.text
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
def on_press(self):
popup = TextInputPopup(self)
popup.open()
def update_changes(self, txt):
self.text = txt
class RV(BoxLayout):
# data_items = ListProperty(newlist)
data_items = ListProperty([])
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_users()
def get_users(self):
# create data_items
for i in list1:
self.data_items.append(i.values())
class TestApp(App):
title = "Kivy RecycleView & SQLite3 Demo"
def build(self):
return RV()
if __name__ == "__main__":
TestApp().run()
test.kv
#:kivy 1.10.0
<TextInputPopup>:
title: "Popup"
size_hint: None, None
size: 400, 400
auto_dismiss: False
BoxLayout:
orientation: "vertical"
TextInput:
id: txtinput
text: root.obj_text
Button:
size_hint: 1, 0.2
text: "Save Changes"
on_release:
root.obj.update_changes(txtinput.text)
root.dismiss()
Button:
size_hint: 1, 0.2
text: "Cancel Changes"
on_release: root.dismiss()
<SelectableButton>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
<RV>:
BoxLayout:
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 9
Label:
text: "Numbers"
Label:
text: "FirstName"
Label:
text: "SecondName"
Label:
text: "MiddleName"
Label:
text: "Grade"
Label:
text: "Names"
Label:
text: "NewFirstName"
Label:
text: "NewSecondName"
Label:
text: "NewThirdName"
BoxLayout:
RecycleView:
viewclass: 'SelectableButton'
data: [{'text': str(x)} for x in root.data_items]
SelectableRecycleGridLayout:
cols: 9
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'horizontal'
multiselect: True
touch_multiselect: True
Question - TableView
There are 8 unique keys and one common key in it, i would like to
create a table from it in kivy with the same order, with keys being
the header of the table.
Solution - Using Kivy RecycleView
Modify the app to extract the keys and values from the collections.OrderedDict
Add a class attribute of type ListProperty e.g. column_headings = ListProperty([])
Implement nested for loop to extract keys or column headings
Implement nested for loop to extract values
Override None with empty string
Snippets
class RV(BoxLayout):
column_headings = ListProperty([])
data_items = ListProperty([])
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_users()
def get_users(self):
# extract keys or column headings
for row in list1:
for key in row.keys():
if key not in self.column_headings:
self.column_headings.append(key)
# extract values
values = []
for row in list1:
for key in self.column_headings:
try:
values.append(str(row[key]))
del row[key]
except KeyError:
values.append(None)
# replace None with empty string
self.data_items = ['' if x is None else x for x in values]
Output

How to retrieve data from sqlite Db and set to kivy TextInput fields?

I'm learning kivy by making small applications from kivy docs and other online resources. The current code has
two textinput fields (UserID, UserName) to store values in the db, using RecycleView the stored data is displayed
on buttons with the Kivy GUI.
On button press, I require corresponding data from the db to be set to the respective textinput fields. i.e. On
pressing button with UserID 1 , textinput field should display values of UserID and UserNames from that row.
main.py
import sqlite3
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
class RV(BoxLayout):
''' Creates Db conn, table, and saves data, retrives stored data and
displays in the RecycleView .'''
data_items = ListProperty([])
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.create_table()
self.get_users()
def create_table(self):
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
sql = """CREATE TABLE IF NOT EXISTS Users(
UserID integer PRIMAY KEY,
UserName text NOT NULL)"""
cursor.execute(sql)
connection.close()
def get_users(self):
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM Users ORDER BY UserID ASC")
rows = cursor.fetchall()
# create data_items
for row in rows:
for col in row:
self.data_items.append(col)
def save(self):
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
UserID = self.ids.no.text
UserName = self.ids.name.text
try:
save_sql="INSERT INTO Users (UserID, UserName) VALUES (?,?)"
connection.execute(save_sql,(UserID, UserName))
connection.commit()
connection.close()
except sqlite3.IntegrityError as e:
print("Error: ",e)
class TestApp(App):
title = "Kivy RecycleView & SQLite3 Demo"
def build(self):
return RV()
if __name__ == "__main__":
TestApp().run()
test.kv
#:kivy 1.10.0
<TextInputPopup>:
title: "Popup"
size_hint: None, None
size: 400, 400
auto_dismiss: False
BoxLayout:
orientation: "vertical"
TextInput:
id: txtinput
text: root.obj_text
Button:
size_hint: 1, 0.2
text: "Save Changes"
on_release:
root.obj.update_changes(txtinput.text)
root.dismiss()
Button:
size_hint: 1, 0.2
text: "Cancel Changes"
on_release: root.dismiss()
<SelectableButton>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
<RV>:
BoxLayout:
orientation: "vertical"
user_no_text_input: no
user_name_text_input: name
Label:
text: "USER NUMBER"
size_hint: (.5, None)
height: 30
TextInput:
id: no
size_hint: (.5, None)
height: 30
multiline: False
Label:
text: "USER NAME"
size_hint: (.5, None)
height: 30
TextInput:
id: name
size_hint: (.5, None)
height: 30
multiline: False
Button:
id: save_btn
text: "SAVE BUTTON"
height: 50
width: 100
on_press: root.save()
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 2
Label:
text: "User ID"
Label:
text: "User Name"
BoxLayout:
RecycleView:
viewclass: 'SelectableButton'
data: [{'text': str(x)} for x in root.data_items]
SelectableRecycleGridLayout:
cols: 2
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
Solution
The solution is as follow: Please refer to snippets, example, and output for details.
kv file
Add on_press event under class rule, <SelectableButton>:. When on_press event is fire, it will invoke root.on_press(self) method in the root class, RV, and pass an instance of the button, self.
Move the two ObjecProperty hooks (user_no_text_input: no, user_name_text_input: name) to the right location i.e. from under BoxLayout: to <RV>:.
Replace data: [{'text': str(x)} for x in root.data_items] with data: root.data_items
Snippet - kv
<SelectableButton>:
...
on_press:
app.root.on_press(self)
<RV>:
user_no_text_input: no
user_name_text_input: name
BoxLayout:
orientation: "vertical"
Label:
...
BoxLayout:
RecycleView:
viewclass: 'SelectableButton'
data: root.data_items
SelectableRecycleGridLayout:
Python Code
In class RV, do the following:
Add NumericProperty to import statement for kivy.properties.
Add ObjecProperty for user_no_text_input = ObjectProperty(None) and user_name_text_input = ObjectProperty(None)
Add NumericProperty for total_col_headings = NumericProperty(0)
Create a on_press() method for the on_press event.
Create a get_table_column_headings() method to get the total column headings in the table. This is used to create the column range.
Enhance get_users() method, to create a list with db column value, db primary key value, and db column range. The trick of using database column range is for populating the TextInput widgets with values from the row clicked/pressed.
Snippet - Python
from kivy.properties import BooleanProperty, ListProperty, NumericProperty, ObjectProperty
...
class RV(BoxLayout):
''' Creates Db conn, table, and saves data, retrives stored data and
displays in the RecycleView .'''
data_items = ListProperty([])
user_no_text_input = ObjectProperty(None)
user_name_text_input = ObjectProperty(None)
total_col_headings = NumericProperty(0)
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.create_table()
self.get_table_column_headings()
self.get_users()
def on_press(self, instance):
columns = self.data_items[instance.index]['range']
self.user_no_text_input.text = self.data_items[columns[0]]['text']
self.user_name_text_input.text = self.data_items[columns[1]]['text']
def get_table_column_headings(self):
connection = sqlite3.connect("demo.db")
with connection:
# With the with keyword, the Python interpreter automatically releases the resources.
# It also provides error handling
cursor = connection.cursor()
cursor.execute("PRAGMA table_info(Users)")
col_headings = cursor.fetchall()
self.total_col_headings = len(col_headings)
...
def get_users(self):
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM Users ORDER BY UserID ASC")
rows = cursor.fetchall()
# create list with db column, db primary key, and db column range
data = []
low = 0
high = self.total_col_headings - 1
for row in rows:
for col in row:
data.append([col, row[0], [low, high]])
low += self.total_col_headings
high += self.total_col_headings
# create data_items
self.data_items = [{'text': str(x[0]), 'Index': str(x[1]), 'range': x[2]} for x in data]
Example
main.py
import sqlite3
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.properties import BooleanProperty, ListProperty, NumericProperty, ObjectProperty
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
class RV(BoxLayout):
''' Creates Db conn, table, and saves data, retrives stored data and
displays in the RecycleView .'''
data_items = ListProperty([])
user_no_text_input = ObjectProperty(None)
user_name_text_input = ObjectProperty(None)
total_col_headings = NumericProperty(0)
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.create_table()
self.get_table_column_headings()
self.get_users()
def on_press(self, instance):
columns = self.data_items[instance.index]['range']
self.user_no_text_input.text = self.data_items[columns[0]]['text']
self.user_name_text_input.text = self.data_items[columns[1]]['text']
def get_table_column_headings(self):
connection = sqlite3.connect("demo.db")
with connection:
# With the with keyword, the Python interpreter automatically releases the resources.
# It also provides error handling
cursor = connection.cursor()
cursor.execute("PRAGMA table_info(Users)")
col_headings = cursor.fetchall()
self.total_col_headings = len(col_headings)
def create_table(self):
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
sql = """CREATE TABLE IF NOT EXISTS Users(
UserID integer PRIMAY KEY,
UserName text NOT NULL)"""
cursor.execute(sql)
connection.close()
def get_users(self):
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
cursor.execute("SELECT * FROM Users ORDER BY UserID ASC")
rows = cursor.fetchall()
# create list with db column, db primary key, and db column range
data = []
low = 0
high = self.total_col_headings - 1
for row in rows:
for col in row:
data.append([col, row[0], [low, high]])
low += self.total_col_headings
high += self.total_col_headings
# create data_items
self.data_items = [{'text': str(x[0]), 'Index': str(x[1]), 'range': x[2]} for x in data]
def save(self):
connection = sqlite3.connect("demo.db")
cursor = connection.cursor()
UserID = self.user_no_text_input.text
UserName = self.user_name_text_input.text
try:
save_sql = "INSERT INTO Users (UserID, UserName) VALUES (?,?)"
cursor.execute(save_sql, (UserID, UserName))
connection.commit()
connection.close()
except sqlite3.IntegrityError as e:
print("Error: ", e)
class TestApp(App):
title = "Kivy RecycleView & SQLite3 Demo"
def build(self):
return RV()
if __name__ == "__main__":
TestApp().run()
test.kv
#:kivy 1.11.0
<SelectableButton>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
on_press:
app.root.on_press(self)
<RV>:
user_no_text_input: no
user_name_text_input: name
BoxLayout:
orientation: "vertical"
Label:
text: "USER NUMBER"
size_hint: (.5, None)
height: 30
TextInput:
id: no
size_hint: (.5, None)
height: 30
multiline: False
Label:
text: "USER NAME"
size_hint: (.5, None)
height: 30
TextInput:
id: name
size_hint: (.5, None)
height: 30
multiline: False
Button:
id: save_btn
text: "SAVE BUTTON"
height: 50
width: 100
on_press: root.save()
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 2
Label:
text: "User ID"
Label:
text: "User Name"
BoxLayout:
RecycleView:
viewclass: 'SelectableButton'
data: root.data_items
SelectableRecycleGridLayout:
cols: 2
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
Output

Change variable via selected item in Kivy

So I learning Kivy but I am stuck with the ListView or, as the ListView seems to be deprecated, the RecycleView.
My problem is that I want the label with species_text as ID to change based on the item I click on, once in the label is in view.
The documentation helped me as far as making the SelectableLabel and being able to click / color it, but I do not know how to change the text of species_text via the data list of the RecycleView or how to save the data list in the ScreenTest class.
Here is my code:
from kivy.app import App
from kivy.uix.button import Label, Button
from kivy.lang import Builder
from kivy.properties import BooleanProperty
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.screenmanager import ScreenManager, Screen
Builder.load_string("""
<ScreenTest>:
Label:
pos_hint: {"x": .45, "top": 1}
text: "Headline"
size_hint: .1, .1
BoxLayout:
pos_hint: {"x": 0.02, "top": .8}
RecycleView:
id: species_list_view
data: [{'name': "Species1", "text": "S1"}, {'name': "Species2", "text": "S2"}]
viewclass: 'SelectableLabel'
SelectableRecycleBoxLayout:
default_size: None, dp(56)
default_size_hint: 1, None
size_hint_y: None
orientation: 'vertical'
multiselect: False
touch_multiselect: False
Label:
id: species_text
text: "Speciestext"
BoxLayout:
size_hint_y: None
height: 30
spacing: 10
canvas:
Color:
rgba: .5, .2, .1, 1
Rectangle:
pos: self.pos
size: self.size
Button:
text: "Go Back"
Button:
text: "Next"
<SelectableLabel>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
""")
class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleBoxLayout):
pass
class SelectableLabel(RecycleDataViewBehavior, Label):
''' Add selection support to the Label '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableLabel, self).refresh_view_attrs(
rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableLabel, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
if is_selected:
print("selection changed to {0}".format(rv.data[index]))
else:
print("selection removed for {0}".format(rv.data[index]))
class ScreenTest(Screen):
pass
screen_manager = ScreenManager()
screen_manager.add_widget(ScreenTest(name="screen_test"))
class TestApp(App):
def build(self):
return screen_manager
test_app = TestApp()
test_app.run()
Thanks for your help!
The apply_selection() method has RecycleView arguments, taking into account that we can create a property that has the selected text, and then we make a bind with the text of the Label:
...
RecycleView:
id: species_list_view
data: [{'name': "Species1", "text": "S1"}, {'name': "Species2", "text": "S2"}]
viewclass: 'SelectableLabel'
text_selected: "" # create property
SelectableRecycleBoxLayout:
...
Label:
id: species_text
text: "Speciestext" if not species_list_view.text_selected else species_list_view.text_selected # apply binding
...
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
if is_selected:
print("selection changed to {0}".format(rv.data[index]))
rv.text_selected = rv.data[index]['text'] # set text
else:
print("selection removed for {0}".format(rv.data[index]))
When you select the SelectableLabel you must find the "species_text" Label and change its text.
One way to do that is from its "apply_selection" method.
if is_selected:
for screen in App.get_running_app().root.screens:
if screen.name == "screen_test":
screen.ids.species_text.text = rv.data[index]["name"]
P.S. There is a typo in the kv code:
The "touch_multiselect" attribute is written "touc_multiselect"

How to use same form code for add,update

test.kv
:kivy 1.10.0
<CRUD>:
title: self.mode + " State"
size_hint: None, None
size: 350, 350
auto_dismiss: False
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
Label:
text: root.label_rec_id
Label:
id: userid
text: root.col_data[0] # root.userid
Label:
text: "First Name"
TextInput:
id: fname
text: root.col_data[1] # root.fname
Label:
text: "Last Name"
TextInput:
id: lname
text: root.col_data[2] # root.lname
Button:
size_hint: 1, 0.4
text: "Save Changes"
on_release:
root.package_changes(fname.text, lname.text)
app.root.update_changes(root)
root.dismiss()
Button:
size_hint: 1, 0.4
text: "Cancel Changes"
on_release: root.dismiss()
when click on any row then edit form open.Can i use same form for add user.
At this time i click on add user then user.py file run and open a new form.how to use same form for both add update.
Yes, you can use the same form to add city. In the example, I added a button, a method add_record, some variable e.g. mode of type StringProperty, and INSERT SQL command. Please refer to the example for details.
Example
main.py
import kivy
kivy.require('1.10.0') # replace with your current kivy version !
import sqlite3 as lite
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty
from kivy.lang import Builder
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from kivy.core.window import Window
Window.size = (500, 500)
MAX_TABLE_COLS = 3
con = lite.connect('company.db')
# con.text_factory = str
cur = con.cursor()
class CRUD(Popup):
"""CRUD - Create, Read, Update, Delete"""
label_id_text = ObjectProperty(None)
label_id_data = ObjectProperty(None)
mode = StringProperty("")
label_rec_id = StringProperty("UserID")
start_point = NumericProperty(0)
col_data = ListProperty(["", "", ""])
def __init__(self, obj, **kwargs):
super(CRUD, self).__init__(**kwargs)
self.mode = obj.mode
if obj.mode == "Add":
self.label_id_text.opacity = 0 # invisible
self.label_id_data.opacity = 0 # invisible
else:
self.label_id_text.opacity = 1 # visible
self.label_id_data.opacity = 1 # visible
self.start_point = obj.start_point
self.col_data[0] = obj.rv_data[obj.start_point]["text"]
self.col_data[1] = obj.rv_data[obj.start_point + 1]["text"]
self.col_data[2] = obj.rv_data[obj.start_point + 2]["text"]
def package_changes(self, fname, lname):
self.col_data[1] = fname
self.col_data[2] = lname
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
rv_data = ObjectProperty(None)
start_point = NumericProperty(0)
mode = StringProperty("")
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
self.rv_data = rv.data
def on_press(self):
self.mode = "Update"
self.start_point = 0
end_point = MAX_TABLE_COLS
rows = len(self.rv_data) // MAX_TABLE_COLS
for row in range(rows):
if self.index in list(range(end_point)):
break
self.start_point += MAX_TABLE_COLS
end_point += MAX_TABLE_COLS
popup = CRUD(self)
popup.open()
class RV(BoxLayout):
rv_data = ListProperty([])
start_point = NumericProperty(0)
mode = StringProperty("")
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_users()
def get_users(self):
'''This result retrieve from database'''
self.rv_data = []
cur.execute("SELECT * FROM Users ORDER BY UserID ASC")
rows = cur.fetchall()
# create data_items
for row in rows:
for col in row:
self.rv_data.append(col)
def add_record(self):
self.mode = "Add"
popup = CRUD(self)
popup.open()
def update_changes(self, obj):
if obj.mode == "Add":
# insert record into Database Table
cur.execute("INSERT INTO Users VALUES(NULL, ?, ?)",
(obj.col_data[1], obj.col_data[2]))
else:
# update Database Table
cur.execute("UPDATE Users SET FirstName=?, LastName=? WHERE UserID=?",
(obj.col_data[1], obj.col_data[2], obj.col_data[0]))
con.commit()
self.get_users()
class ListUser(App):
title = "Users"
def build(self):
self.root = Builder.load_file('main.kv')
return RV()
if __name__ == '__main__':
ListUser().run()
main.kv
#:kivy 1.10.0
<CRUD>:
label_id_text: label_id_text
label_id_data: label_id_data
title: self.mode + " State"
size_hint: None, None
size: 350, 350
auto_dismiss: False
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
Label:
id: label_id_text
text: "ID"
Label:
id: label_id_data
text: root.col_data[0] # root.userid
Label:
text: "First Name"
TextInput:
id: fname
text: root.col_data[1] # root.fname
Label:
text: "Last Name"
TextInput:
id: lname
text: root.col_data[2] # root.lname
Button:
size_hint: 1, 0.4
text: "Confirm " + root.mode
on_release:
root.package_changes(fname.text, lname.text)
app.root.update_changes(root)
root.dismiss()
Button:
size_hint: 1, 0.4
text: "Cancel " + root.mode
on_release: root.dismiss()
<SelectableButton>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
<RV>:
BoxLayout:
orientation: "vertical"
Button:
size_hint: 1, 0.1
text: "Add Record"
on_press: root.add_record()
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 3
Label:
text: "ID"
Label:
text: "First Name"
Label:
text: "Last Name"
BoxLayout:
RecycleView:
viewclass: 'SelectableButton'
data: [{'text': str(x)} for x in root.rv_data]
SelectableRecycleGridLayout:
cols: 3
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
Output

How to run python script from another .py file and show in current window

menu.py
from kivy.app import App
from kivy.uix.dropdown import DropDown
from kivy.lang import Builder
class CustDrop(DropDown):
def __init__(self, **kwargs):
super(CustDrop, self).__init__( **kwargs)
self.select('')
kv_str = Builder.load_string('''
BoxLayout:
orientation: 'vertical'
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: (1,1,1)
size_hint_y:1
Button:
id: btn
text: 'user'
on_release: dropdown.open(self)
#size_hint_y: None
#height: '48dp'
CustDrop:
id: dropdown
Button:
text: 'List User'
size_hint_y: None
height: '48dp'
Label:
size_hint_x: 4
Label:
size_hint_y: 9
''')
class ExampleApp(App):
def build(self):
return kv_str
if __name__ =='__main__':
ExampleApp().run()
user.py
import kivy
kivy.require('1.9.0') # replace with your current kivy version !
import sqlite3 as lite
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty,NumericProperty
from kivy.lang import Builder
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
from kivy.core.window import Window
Window.size = (500, 500)
#con = lite.connect('user.db')
#con.text_factory = str
#cur = con.cursor()
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
def on_press(self,*args):
popup = TextInputPopup(self)
popup.open()
def update_changes(self):
self.text = txt
class RV(BoxLayout):
data_items = ListProperty([])
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_users()
def get_users(self):
# cur.execute("SELECT * FROM `users` order by id asc")
# rows = cur.fetchall()
rows = [(1, 'Yash', 'Chopra'),(2, 'amit', 'Kumar')]
for row in rows:
for col in row:
self.data_items.append(col)
class ListUser(App):
title = "Users"
def build(self):
self.root = Builder.load_file('user.kv')
return RV()
if __name__ == '__main__':
ListUser().run()
user.kv
#:kivy 1.10.0
<SelectableButton>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
<RV>:
BoxLayout:
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 3
Label:
text: "ID"
Label:
text: "First Name"
Label:
text: "Last Name"
BoxLayout:
RecycleView:
viewclass: 'SelectableButton'
data: [{'text': str(x)} for x in root.data_items]
SelectableRecycleGridLayout:
cols: 3
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
I have two file menu.py and user.py. menu.py file show menu and user.py shows list of user..
when i run menu.py then shows user menu on top .When i click on user then 'list user' show(submenu of user).When i click on 'list user' then user list should show in current window.Menu will be on top and user-list show in same window(under menu).
To dsiplay the user list in the same window, combine both Python scripts and kv files into one. Please refer to the example below for details.
Example
mainmenu.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.dropdown import DropDown
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.button import Button
from kivy.uix.recyclegridlayout import RecycleGridLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from kivy.uix.popup import Popup
import sqlite3 as lite
dbPath = "/home/iam/dev/SQLite/sampleDB/ChinookDB/"
#con = lite.connect('user.db')
con = lite.connect(dbPath + "chinook.db")
#con.text_factory = str
cur = con.cursor()
class MessageBox(Popup):
obj = ObjectProperty(None)
obj_text = StringProperty("")
def __init__(self, obj, **kwargs):
super(MessageBox, self).__init__(**kwargs)
self.obj = obj
self.obj_text = obj.text
class SelectableRecycleGridLayout(FocusBehavior, LayoutSelectionBehavior,
RecycleGridLayout):
''' Adds selection and focus behaviour to the view. '''
class SelectableButton(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButton, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButton, self).on_touch_down(touch):
return True
if self.collide_point(*touch.pos) and self.selectable:
return self.parent.select_with_touch(self.index, touch)
def apply_selection(self, rv, index, is_selected):
''' Respond to the selection of items in the view. '''
self.selected = is_selected
def on_press(self):
popup = MessageBox(self)
popup.open()
def update_changes(self, txt):
self.text = txt
class RV(BoxLayout):
data_items = ListProperty([])
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_users()
def get_users(self):
cur.execute("SELECT CustomerId, FirstName, LastName FROM 'customers' order by CustomerId asc")
rows = cur.fetchall()
for row in rows:
for col in row:
self.data_items.append(col)
class CustDrop(DropDown):
def __init__(self, **kwargs):
super(CustDrop, self).__init__(**kwargs)
self.select('')
class MainMenu(BoxLayout):
users = ObjectProperty(None)
dropdown = ObjectProperty(None)
def display_users(self):
# rv = RV()
self.dropdown.dismiss()
self.users.add_widget(RV())
class MainMenuApp(App):
title = "Example"
def build(self):
return MainMenu()
if __name__ == '__main__':
MainMenuApp().run()
mainmenu.kv
#:kivy 1.10.0
<MessageBox>:
title: "Popup"
size_hint: None, None
size: 400, 400
auto_dismiss: False
BoxLayout:
orientation: "vertical"
TextInput:
id: txtinput
text: root.obj_text
Button:
size_hint: 1, 0.2
text: "Save Changes"
on_release:
root.obj.update_changes(txtinput.text)
root.dismiss()
Button:
size_hint: 1, 0.2
text: "Cancel Changes"
on_release: root.dismiss()
<SelectableButton>:
# Draw a background to indicate selection
canvas.before:
Color:
rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
Rectangle:
pos: self.pos
size: self.size
<RV>:
BoxLayout:
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 3
Label:
text: "ID"
Label:
text: "First Name"
Label:
text: "Last Name"
BoxLayout:
RecycleView:
viewclass: 'SelectableButton'
data: [{'text': str(x)} for x in root.data_items]
SelectableRecycleGridLayout:
cols: 3
default_size: None, dp(26)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
multiselect: True
touch_multiselect: True
<MainMenu>:
users: users
dropdown: dropdown
orientation: 'vertical'
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: (1,1,1)
size_hint_y:1
Button:
id: btn
text: 'user'
on_release: dropdown.open(self)
CustDrop:
id: dropdown
Button:
text: 'List User'
size_hint_y: None
height: '48dp'
on_release: root.display_users()
Label:
size_hint_x: 4
text: "label 1"
BoxLayout:
id: users
size_hint_y: 9
Output

Categories

Resources