python/Kivy : How to pass value of textbox in new window - python

I have two file demo.py and demo.kv.
When i run demo.py and click on +Add then screen shows looks like.I want value of name textbox in def add_row(self): function when click on button.When i click on button of first row then i want to get test1 in def add_row(self): which are in class RowsExtra(BoxLayout): and click on button of second row then get test2.I want to get test1 value in textName variable.After that i am fetching data from database according name textbox value.
def add_row(self):
print("here,i want value of name(`test1`) when click on button")
textName = 'test1'
#cur.execute("SELECT `column_name` FROM `table_name` WHERE `name`=?", (textName,))
#rows = cur.fetchone()
rows = [('A1'), ('B1'), ('C1'), ('D1')]
for row in rows:
self.row_count += 1
r = RowExtra(button_text=str(self.row_count))
r.col_data[1] = row
self.add_widget(r)
demo.py
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 BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty
from kivy.uix.popup import Popup
Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (500, 400)
class User(Popup):
total_value = ObjectProperty(None)
def __init__(self, **kwargs):
super(User, self).__init__(**kwargs)
def add_more(self):
self.ids.rows.add_more()
class ExtraPopup(Popup):
mode = StringProperty("")
def __init__(self, obj, **kwargs):
super(ExtraPopup, self).__init__(**kwargs)
def add_extra(self):
self.ids.rowsExtra.add_row()
class RowExtra(BoxLayout):
col_data = ListProperty(["?", "?", "?", "?", "?", "?", "?", "?"])
button_text = StringProperty("")
mode = StringProperty("")
def __init__(self, **kwargs):
super(RowExtra, self).__init__(**kwargs)
self.col_data[0] = ''
self.col_data[1] = ''
self.col_data[2] = ''
class RowsExtra(BoxLayout):
#orientation = "vertical"
row_count = 0
button_text = StringProperty("")
def __init__(self, **kwargs):
super(RowsExtra, self).__init__(**kwargs)
self.add_row()
def add_row(self):
print("here,i want value of name(`test1`) when click on button")
textName = 'test1'
#cur.execute("SELECT `column_name` FROM `table_name` WHERE `name`=?", (textName,))
#rows = cur.fetchone()
rows = [('A1'), ('B1'), ('C1'), ('D1')]
for row in rows:
self.row_count += 1
r = RowExtra(button_text=str(self.row_count))
r.col_data[1] = row
self.add_widget(r)
class Row(BoxLayout):
col_data = ListProperty(["?", "?", "?", "?", "?"])
name = ObjectProperty(None)
button_text = StringProperty("")
col_data3 = StringProperty("")
col_data4 = StringProperty("")
def __init__(self, **kwargs):
super(Row, self).__init__(**kwargs)
def add_seller_expenses(self):
self.mode = "Add"
popup = ExtraPopup(self)
popup.open()
class Rows(BoxLayout):
row_count = 0
def __init__(self, **kwargs):
super(Rows, self).__init__(**kwargs)
self.add_more()
def add_more(self):
self.row_count += 1
self.add_widget(Row(button_text=str(self.row_count)))
class rv(BoxLayout):
data_items = ListProperty([])
mode = StringProperty("")
def __init__(self, **kwargs):
super(rv, self).__init__(**kwargs)
def add(self):
self.mode = "Add"
popup = User()
popup.open()
class MainMenu(BoxLayout):
content_area = ObjectProperty()
def display(self):
self.rv = rv()
self.content_area.add_widget(self.rv)
class demo(App):
def build(self):
return MainMenu()
if __name__ == '__main__':
demo().run()
demo.kv
<Row>:
size_hint_y: None
height: self.minimum_height
height: 40
Button:
text: root.button_text
size_hint_x: None
top: 200
TextInput:
id : name
text: root.col_data3
width: 300
TextInput:
id: number_input
text: root.col_data4
width: 300
input_filter: 'int'
Button:
text: "Button"
size_hint_x: None
top: 200
on_press: root.add_seller_expenses()
<Rows>:
size_hint_y: None
height: self.minimum_height
orientation: "vertical"
<User>:
id: 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()
<rv>:
BoxLayout:
orientation: "vertical"
Button:
size_hint: .25, .03
text: "+Add"
on_press: root.add()
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 3
BoxLayout:
orientation: "vertical"
<ExtraPopup>:
title: " Extra"
title_size: 20
title_font: "Verdana"
size_hint: None, None
size: 400, 400
auto_dismiss: False
BoxLayout:
orientation: "vertical"
padding : 10, 5
spacing: 10, 10
BoxLayout:
orientation: "horizontal"
spacing: 10, 10
size: 550, 30
size_hint: 1, None
Label:
size_hint_x: .3
text: "SN"
text_size: self.size
valign: 'bottom'
halign: 'center'
Label:
size_hint_x: .7
text: "Name"
text_size: self.size
valign: 'bottom'
halign: 'center'
ScrollView:
RowsExtra:
id: rowsExtra
BoxLayout:
orientation: "horizontal"
size_hint_x: .3
size_hint: .15, .1
Button:
#size_hint_x: .2
text: "+Add More"
valign: 'bottom'
on_press: root.add_extra()
BoxLayout:
orientation: "horizontal"
padding : 10, 5
spacing: 10, 10
size_hint: .5, .2
pos_hint: {'x': .25, 'y':.25}
Button:
text: 'Ok'
id: ok_text
on_release:
root.dismiss()
Button:
text: 'Cancel'
#size_hint_x: .5
on_release: root.dismiss()
<RowExtra>:
size_hint_y: None
height: self.minimum_height
height: 30
Button:
text: root.button_text
size_hint_x: .3
#top: 200
TextInput:
text: root.col_data[1]
size_hint_x: .7
<RowsExtra>:
size_hint_y: None
height: self.minimum_height
orientation: "vertical"
<MenuButton#Button>:
text_size: self.size
valign: "middle"
padding_x: 5
size : (100, 40)
size_hint : (None, None)
background_color: 90 , 90, 90, 90
background_normal: ''
color: 0, 0.517, 0.705, 1
border: (0, 10, 0, 0)
<MainMenu>:
content_area: content_area
BoxLayout:
orientation: 'vertical'
spacing : 10
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
size_hint_y: 2
MenuButton:
text: 'Menu'
size : (50, 12)
on_release: root.display()
BoxLayout:
id: content_area
size_hint_y: 30

A possible solution is to access rowsExtra through the popup since it is your child, but one problem is that you call add_row() in the constructor before it is assigned a parent (the assignment of a parent is after the creation of the object), we must eliminate that instruction and call it again before opening the popup. To store the text we can create a property of type StringProperty.
[...]
class RowsExtra(BoxLayout):
#orientation = "vertical"
row_count = 0
button_text = StringProperty("")
textName = StringProperty("")
def __init__(self, **kwargs):
super(RowsExtra, self).__init__(**kwargs)
def add_row(self):
print("here,i want value of name(`test1`) when click on button")
print(self.textName)
#cur.execute("SELECT `column_name` FROM `table_name` WHERE `name`=?", (textName,))
#rows = cur.fetchone()
rows = [('A1'), ('B1'), ('C1'), ('D1')]
for row in rows:
self.row_count += 1
r = RowExtra(button_text=str(self.row_count))
r.col_data[1] = row
self.add_widget(r)
class Row(BoxLayout):
col_data = ListProperty(["?", "?", "?", "?", "?"])
name = ObjectProperty(None)
button_text = StringProperty("")
col_data3 = StringProperty("")
col_data4 = StringProperty("")
def __init__(self, **kwargs):
super(Row, self).__init__(**kwargs)
def add_seller_expenses(self):
self.mode = "Add"
popup = ExtraPopup(self)
popup.ids.rowsExtra.textName = self.ids.name.text
popup.ids.rowsExtra.add_row()
popup.open()
[...]

Related

Stopping RecycleView from sorting items

In one part of my program I have a RecycleView that uses a RecycleBoxLayout and together they hold a bunch of DownloadItem instances which itself inherits from MDCard.
The problem with the recycleview is that it sorts the items in an absurd way. I would like the items to be shown in the order that they were added, not be sorted by the recycleview.
Example:
RecycleView sorting items
My Python file:
from kivy.lang import Builder
from kivy.properties import StringProperty, ColorProperty
from kivy.animation import Animation
from kivymd.uix.card import MDCard
from kivymd.app import MDApp
class DownloadItem(MDCard):
path = StringProperty()
url_type = StringProperty("file")
def __init__(self, **kwargs):
self.paused = False
self.fill_animation = None
super(DownloadItem, self).__init__(**kwargs)
def pause_resume_download(self):
if not self.paused:
self.ids.pause_resume_button.icon = "play"
if self.fill_animation is not None:
self.fill_animation.cancel(self.ids.progress_bar)
self.paused = True
else:
self.ids.pause_resume_button.icon = "pause"
self.fill_animation = Animation(value=100, duration=4)
self.fill_animation.bind(on_complete=lambda *args: Animation(color=self.theme_cls.accent_color,
duration=Example.color_duration)
.start(self.ids.progress_bar))
self.fill_animation.start(self.ids.progress_bar)
self.paused = False
Animation(color=app.pause_color if self.paused else self.theme_cls.primary_color,
duration=Example.color_duration).start(self.ids.progress_bar)
def cancel_download(self):
if self.fill_animation is not None:
self.fill_animation.cancel(self.ids.progress_bar)
Animation(color=app.fail_color,
duration=Example.color_duration).start(self.ids.progress_bar)
class Example(MDApp):
fail_color = ColorProperty([255 / 255, 99 / 255, 71 / 255, 1.0])
pause_color = ColorProperty([240 / 255, 163 / 255, 10 / 255, 1.0])
success_color = ColorProperty(None)
color_duration = .15
def __init__(self, **kwargs):
global app
super(Example, self).__init__(**kwargs)
self.kv = Builder.load_file("design.kv")
self.path = "C:/Users/Family/Downloads/"
app = self
def build(self):
self.theme_cls.theme_style = "Dark"
return self.kv
def add_item(self):
self.kv.ids.downloads_list.data.append({"path": self.path + '/' if self.path[-1] != '/' else self.path,
"url_type": "file"})
if __name__ == '__main__':
Example().run()
My KV file:
#:kivy 2.0.0
<TooltipMDLabel#MDLabel+MDTooltip>
<DownloadItem>:
orientation: "vertical"
padding: 10
spacing: 10
size_hint_y: None
height: 100
elevation: 20
border_radius: 5
radius: [5]
MDBoxLayout:
adaptive_height: True
spacing: 5
MDIcon:
icon: root.url_type
size_hint_x: None
width: self.texture_size[0]
TooltipMDLabel:
text: root.path if len(root.path) <= 30 else root.path[:31] + " ..."
tooltip_text: f"Path: {root.path}\nType: {root.url_type}"
tooltip_bg_color: app.theme_cls.bg_darkest
tooltip_text_color: app.theme_cls.opposite_bg_darkest
size_hint_y: None
height: self.texture_size[1]
MDSeparator:
MDBoxLayout:
spacing: 10
MDProgressBar:
id: progress_bar
min: 0
max: 100
value: 50
color: app.theme_cls.primary_color
MDIconButton:
id: pause_resume_button
icon: "pause"
pos_hint: {"center_x": .5, "center_y": .5}
on_release: root.pause_resume_download()
MDIconButton:
icon: "close"
pos_hint: {"center_x": .5, "center_y": .5}
on_release: root.cancel_download()
BoxLayout:
orientation: "vertical"
spacing: 10
RecycleView:
id: downloads_list
viewclass: "DownloadItem"
RecycleBoxLayout:
default_size: None, 100
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: "vertical"
padding: 15
spacing: 15
MDRaisedButton:
text: "Add"
size_hint_x: 1
on_release: app.add_item()
The RecycleView does not sort the items. They are presented in the order that they appear in the data. What you are seeing is the "recycle" behavior, where your DownloadItems are recycled, making it appear that they are sorted. Try adding a count number to the display of each DownloadItem, and you will see more clearly what is happening.

How to change the behaviour of a label from another class in kivy

I want to create a page, showing a form and a submit-buttton that when clicked it will take you to another page that will show the data being inputs from the form page.
I created 2 class Form and Profile, but when I clicked the button of form, it will take you to profile page but nothing is change.
I've tried so many things but couldn't do it, please help.
.py file
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty
from kivy.uix.widget import Widget
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
class Manager(ScreenManager):
pass
class Profile(Screen):
profile_name = ObjectProperty()
profile_matric = ObjectProperty()
profile_school = ObjectProperty()
profile_programme = ObjectProperty()
profile_level = ObjectProperty()
def make_changes(self):
self.ids.profile_name = 'New name'
class Form(Screen):
user_name = ObjectProperty()
matric = ObjectProperty()
school = ObjectProperty()
programme = ObjectProperty()
level = ObjectProperty()
def submit(self):
y = Profile()
y.make_changes()
kv = Builder.load_file('main.kv')
class SpinApp(App):
def build(self):
return kv
if __name__ == '__main__':
SpinApp().run()
.kv file
Manager:
Form:
Profile:
<Form#BoxLayout>:
name: 'form'
orientation: 'vertical'
user_name: user_name
matric: matric
school: school
programme: programme
level: level
RelativeLayout:
GridLayout:
cols: 1
#size_hint: (0.8, 0.8)
spacing: 5
padding: [20]
pos_hint: {'center_x':.5, 'center_y':.5}
background_normal: ''
GridLayout:
cols: 2
Label:
text: '\nName'
size_hint_x: None
size: self.texture_size
pos_hint: {'left': 1}
bold: True
size_hint_y: None
height: 80
Input_text:
id: user_name
hint_text: 'enter your full name'
GridLayout:
cols: 2
Input_label:
text: '\nMatric Number'
Input_text:
id: matric
hint_text: 'eg. se/mat-csc/19/0000'
GridLayout:
cols: 2
Input_label:
text: '\nSchool'
Input_text:
id: school
hint_text: 'your school'
GridLayout:
cols: 2
Input_label:
text: '\nLevel'
Input_text:
id: level
hint_text: 'Enter your level'
GridLayout:
cols: 2
Input_label:
text: '\nProgramme'
Input_text:
id: programme
hint_text: 'type your programme'
Button:
text: 'submit'
on_release:
app.root.current = 'profile'
root.submit()
<Profile#BoxLayout>:
name: 'profile'
orientation: 'vertical'
profile_name: profile_name
profile_matric: profile_matric
profile_level: profile_level
profile_school: profile_school
profile_programme: profile_programme
RelativeLayout:
GridLayout:
cols: 1
size_hint: (0.8, 0.8)
spacing: 5
padding: [20]
pos_hint: {'center_x':.5, 'center_y':.5}
background_normal: ''
canvas.before:
Color:
rgba: (253/255, 245/255, 230/255, 1)
RoundedRectangle:
size: self.size
pos: self.pos
radius: [15]
Image:
source: 'slde_1.png'
size: self.texture_size
profile_label:
id: profile_name
text: 'Name: '
profile_label:
id: profile_matric
text: 'Matric no.:'
profile_label:
id: profile_level
text: 'Level:'
profile_label:
id: profile_school
text: 'School:'
profile_label:
id: profile_programme
text: 'Programme:'
<profile_label#Label>:
color: 1,1,1,1
bold: True
font_size: 30
size_hint_y: None
height: 85
text_size: self.size
halign: 'left'
valign: 'middle'
padding: [10,0]
canvas.before:
Color:
rgba: 47/255, 79/255, 79/255, 1
RoundedRectangle:
size: self.size
pos: self.pos
radius: [25]
<Input_label#Label>:
size_hint_x: None
size: self.texture_size
pos_hint: {'left': 1,}
size_hint_y: None
height: 80
bold: True
<Input_text#TextInput>:
multiline: False
size_hint_y: None
height: 80
padding: [10,20]
background_normal: ''
background_color: 240/255, 248/255, 1, 1
valign: 'bottom'
In your Profile class you can add an on_enter() method. The on_enter() method is executed every time the Profile Screen is entered. So something like this:
class Profile(Screen):
profile_name = ObjectProperty()
profile_matric = ObjectProperty()
profile_school = ObjectProperty()
profile_programme = ObjectProperty()
profile_level = ObjectProperty()
def on_enter(self, *args):
form = self.manager.get_screen('form')
self.profile_name.text = form.user_name.text
self.profile_matric.text = form.matric.text
self.profile_school.text = form.school.text
self.profile_programme.text = form.programme.text
self.profile_level.text = form.level.text
Then in your kv, the submit Button can just change the Screen:
Button:
text: 'submit'
on_release:
app.root.current = 'profile'

Python : How to get value of dynmaic row

I am new to python and kivy.
I am trying to get value of dynamic row.But now i am getting value like this
Column2
Column1
Can someone tell me how to get value like this ?
1,column1,column2
2,column1,column2
Because i have three column in my database table like id,name,value and i want to insert value in database table through loop
I am using this code
def insert_value(self):
values = []
rows = self.ids.rows
for row in reversed(rows.children):
for ch in row.children:
if isinstance(ch, TextInput):
values.append(ch.text)
lenArray = len(values)
for x in range(0, lenArray):
print (values[x])
demo.py
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 BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty
from kivy.uix.textinput import TextInput
Window.size = (450, 525)
class display(Screen):
def add_more(self):
self.ids.rows.add_row()
def insert_value(self):
values = []
rows = self.ids.rows
for row in reversed(rows.children):
for ch in row.children:
if isinstance(ch, TextInput):
values.append(ch.text)
lenArray = len(values)
for x in range(0, lenArray):
print (values[x])
class Row(BoxLayout):
button_text = StringProperty("")
id = ObjectProperty(None)
class Rows(BoxLayout):
orientation = "vertical"
row_count = 0
def __init__(self, **kwargs):
super(Rows, self).__init__(**kwargs)
self.add_row()
def add_row(self):
self.row_count += 1
self.add_widget(Row(button_text=str(self.row_count),id=str("test"+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()
demo.kv
<Row>:
orientation: "horizontal"
spacing: 0, 5
Button:
text: root.button_text
size_hint_x: .2
TextInput:
text:"Column1"
size_hint_x: .8
TextInput:
text:"Column2"
size_hint_x: .8
display:
BoxLayout:
orientation: "vertical"
padding : 20, 20
BoxLayout:
orientation: "horizontal"
Button:
size_hint_x: .2
text: "+Add More"
valign: 'bottom'
on_press: root.add_more()
BoxLayout:
orientation: "horizontal"
Label:
size_hint_x: .2
text: "SN"
valign: 'bottom'
Label:
size_hint_x: .8
text: "Value"
valign: 'bottom'
Rows:
id: rows
BoxLayout:
orientation: "horizontal"
padding : 10, 0
spacing: 10, 10
size_hint: .5, .7
pos_hint: {'x': .25, 'y':.25}
Button:
text: 'Ok'
on_release:
root.insert_value()
Button:
text: 'Cancel'
on_release: root.dismiss()
To maintain a structure we must create a list of lists, then in each list the first parameter is the text of the Button that we filter through isinstance(), and the other elements are concatenated.
[...]
from kivy.uix.button import Button
class display(Screen):
def add_more(self):
self.ids.rows.add_row()
def insert_value(self):
values = []
rows = self.ids.rows
for row in reversed(rows.children):
vals = []
for ch in reversed(row.children):
if isinstance(ch, TextInput):
vals.append(ch.text)
if isinstance(ch, Button):
vals.insert(0, ch.text)
values.append(vals)
for val in values:
print("{},{},{}".format(*val))
[...]
One option is to add a ListProperty to your Row class that stores the values of the row in the order you want, which makes it easier to obtain them later.
You can use a ListView to show the rows.
Demo.kv:
<Row>:
values: row_id.text, col1.text, col2.text
orientation: "horizontal"
spacing: 0, 5
size_hint_y: None
height: 30
Button:
id: row_id
text: root.button_text
size_hint_x: .2
TextInput:
id: col1
text:"Column1"
size_hint_x: .8
TextInput:
id: col2
text:"Column2"
size_hint_x: .8
<Rows>:
content: content
BoxLayout:
id: content
orientation: "vertical"
size_hint_y: None
height: self.minimum_height
Display:
rows: rows
BoxLayout:
orientation: "vertical"
padding : 20, 20
BoxLayout:
orientation: "horizontal"
Button:
size_hint_x: .2
text: "+Add More"
valign: 'bottom'
on_press: root.add_more()
BoxLayout:
orientation: "horizontal"
Label:
size_hint_x: .2
text: "SN"
valign: 'bottom'
Label:
size_hint_x: .8
text: "Value"
valign: 'bottom'
Rows:
id: rows
BoxLayout:
orientation: "horizontal"
padding : 10, 10
spacing: 10, 10
size_hint: .5, .7
pos_hint: {'x': .25, 'y':.25}
Button:
text: 'Ok'
on_release:
root.insert_value()
Button:
text: 'Cancel'
on_release: root.dismiss()
Demo.py:
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, ObjectProperty
from kivy.uix.scrollview import ScrollView
from kivy.clock import Clock
Window.size = (450, 525)
class Display(Screen):
rows = ObjectProperty(None)
def __init__(self, **kwargs):
super(Display, self).__init__(**kwargs)
def add_more(self):
self.rows.add_row()
def insert_value(self):
values = [row.values for row in reversed(self.rows.content.children)]
for row in values:
print(row)
class Row(BoxLayout):
button_text = StringProperty("")
id = ObjectProperty(None)
values = ListProperty()
class Rows(ScrollView):
row_count = 0
content = ObjectProperty(None)
def __init__(self, **kwargs):
super(Rows, self).__init__(**kwargs)
Clock.schedule_once(self.add_row)
def add_row(self, *args):
self.row_count += 1
self.content.add_widget(Row(button_text=str(self.row_count),
id="test" + 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()

content dynamically set in one boxlayout

test.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, ObjectProperty,NumericProperty
from kivy.lang import Builder
from kivy.uix.dropdown import DropDown
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.maximize()
from kivy.clock import Clock
from kivy.uix.treeview import TreeView, TreeViewLabel, TreeViewNode
class EditStatePopup(Popup):
col_data = ListProperty(["?", "?", "?"])
index = NumericProperty(0)
def __init__(self, obj, **kwargs):
super(EditStatePopup, self).__init__(**kwargs)
self.index = obj.index
self.col_data[0] = obj.rv_data[self.index]["StateId"]
self.col_data[1] = obj.rv_data[self.index]["StateName"]
self.col_data[2] = obj.rv_data[self.index]["StateCode"]
def package_changes(self, stateName, stateCode):
self.col_data[1] = stateName
self.col_data[2] = stateCode
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)
def __init__(self, **kwargs):
super(SelectableButton, self).__init__(**kwargs)
Clock.schedule_interval(self.update, .0005)
def update(self, *args):
self.text = self.rv_data[self.index][self.key]
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):
self.selected = is_selected
self.rv_data = rv.data
def on_press(self):
popup = EditStatePopup(self)
popup.open()
class RV(BoxLayout):
data_items = ListProperty([])
col1 = ListProperty()
col2 = ListProperty()
col3 = ListProperty()
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_states()
def update(self):
self.col1 = [{'StateId': str(x[0]), 'StateName': x[1], 'StateCode': str(x[2]), 'key': 'StateId'} for x in self.data_items]
self.col2 = [{'StateId': str(x[0]), 'StateName': x[1], 'StateCode': str(x[2]), 'key': 'StateName'} for x in self.data_items]
self.col3 = [{'StateId': str(x[0]), 'StateName': x[1], 'StateCode': str(x[2]), 'key': 'StateCode'} for x in self.data_items]
def get_states(self):
rows = [(1, 'Andaman and Nicobar Islands ', 35), (2, 'Andhra Pradesh', 28), (3, 'Arunachal Pradesh', 12), (4, 'Assam', 18), (5, 'Bihar', 10), (6, 'Chandigarh', 4), (7, 'Chattisgarh', 22)]
i = 0
for row in rows:
self.data_items.append([row[0], row[1], row[2], i])
i += 1
print(self.data_items)
self.update()
def populate_tree_view(tree_view, parent, node):
if parent is None:
tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
is_open=True))
else:
tree_node = tree_view.add_node(TreeViewLabel(text=node['node_id'],
is_open=True), parent)
for child_node in node['children']:
populate_tree_view(tree_view, tree_node, child_node)
rows = [(1, 'Andaman and Nicobar Islands ', 35), (2, 'Andhra Pradesh', 28), (3, 'Arunachal Pradesh', 12), (4, 'Assam', 18), (5, 'Bihar', 10), (6, 'Chandigarh', 4), (7, 'Chattisgarh', 22)]
tree = []
for r in rows:
tree.append({'node_id': r[1], 'children': []})
class TreeviewGroup(Popup):
treeview = ObjectProperty(None)
tv = ObjectProperty(None)
h = NumericProperty(0)
#ti = ObjectProperty()
def __init__(self, **kwargs):
super(TreeviewGroup, self).__init__(**kwargs)
self.tv = TreeView(root_options=dict(text=""),
hide_root=False,
indent_level=4)
for branch in tree:
populate_tree_view(self.tv, None, branch)
#self.remove_widgets()
self.treeview.add_widget(self.tv)
Clock.schedule_once(self.update, 1)
def remove_widgets(self):
for child in [child for child in self.treeview.children]:
self.treeview.remove_widget(child)
def update(self, *args):
self.h = len([child for child in self.tv.children]) * 24
class EditCityPopup(Popup):
col_data = ListProperty(["?", "?", "?", "?", "?"])
index = NumericProperty(0)
popup = ObjectProperty(None)
def __init__(self, obj, **kwargs):
super(EditCityPopup, self).__init__(**kwargs)
self.index = obj.index
self.col_data[0] = obj.rv_data_city[self.index]["cityId"]
self.col_data[1] = obj.rv_data_city[self.index]["stateId"]
self.col_data[2] = obj.rv_data_city[self.index]["cityName"]
self.col_data[3] = obj.rv_data_city[self.index]["shortName"]
self.col_data[4] = obj.rv_data_city[self.index]["pinCode"]
def package_changes(self, stateId, cityName, shortName, pinCode):
self.col_data[1] = stateId
self.col_data[2] = cityName
self.col_data[3] = shortName
self.col_data[4] = pinCode
def display_states_treeview(self, instance):
if len(instance.text) > 0:
if self.popup is None:
self.popup = TreeviewGroup()
self.popup.open()
class SelectableButtonCity(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
rv_data_city = ObjectProperty(None)
start_point = NumericProperty(0)
def __init__(self, **kwargs):
super(SelectableButtonCity, self).__init__(**kwargs)
Clock.schedule_interval(self.update, .0005)
def update(self, *args):
self.text = self.rv_data_city[self.index][self.key]
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButtonCity, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButtonCity, 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_city = rv.data
def on_press(self):
popup = EditCityPopup(self)
popup.open()
class RVCITY(BoxLayout):
data_items_city = ListProperty([])
col1 = ListProperty()
col2 = ListProperty()
col3 = ListProperty()
col4 = ListProperty()
col5 = ListProperty()
def __init__(self, **kwargs):
super(RVCITY, self).__init__(**kwargs)
self.get_cities()
def update(self):
self.col1 = [{'cityId': str(x[0]), 'stateId': str(x[1]), 'cityName': str(x[2]), 'shortName': str(x[3]), 'pinCode': str(x[4]), 'key': 'cityId'} for x in self.data_items_city]
self.col2 = [{'cityId': str(x[0]), 'stateId': str(x[1]), 'cityName': str(x[2]), 'shortName': str(x[3]), 'pinCode': str(x[4]), 'key': 'stateId'} for x in self.data_items_city]
self.col3 = [{'cityId': str(x[0]), 'stateId': str(x[1]), 'cityName': str(x[2]), 'shortName': str(x[3]), 'pinCode': str(x[4]), 'key': 'cityName'} for x in self.data_items_city]
self.col4 = [{'cityId': str(x[0]), 'stateId': str(x[1]), 'cityName': str(x[2]), 'shortName': str(x[3]), 'pinCode': str(x[4]), 'key': 'shortName'} for x in self.data_items_city]
self.col5 = [{'cityId': str(x[0]), 'stateId': str(x[1]), 'cityName': str(x[2]), 'shortName': str(x[3]), 'pinCode': str(x[4]), 'key': 'pinCode'} for x in self.data_items_city]
def get_cities(self):
rows = [(1, 'Bihar', 'Patna', 'Patna', 801108), (2, 'Andaman and Nicobar Islands ', 'Port Blair', 'PB', 744101), (3, 'Assam', 'Guwahati', 'Guwahati', 781001), (4, 'Assam', 'Nagaon', 'Nagaon', 782120), (5, 'Chandigarh', 'Amritsar', 'Amritsar', 143502), (6, 'Andhra Pradesh', 'Visakhapatnam', 'VP', 531219), (7, 'Chattisgarh', 'Bilaspur', 'Bilaspur', 495001)]
i = 0
for row in rows:
self.data_items_city.append([row[0], row[1], row[2], row[3], row[4], i])
i += 1
print(self.data_items_city)
self.update()
class EditAreaPopup(Popup):
col_data = ListProperty(["?", "?", "?"])
index = NumericProperty(0)
popup = ObjectProperty(None)
def __init__(self, obj, **kwargs):
super(EditAreaPopup, self).__init__(**kwargs)
self.index = obj.index
self.col_data[0] = obj.rv_data_area[self.index]["areaId"]
self.col_data[1] = obj.rv_data_area[self.index]["cityId"]
self.col_data[2] = obj.rv_data_area[self.index]["areaName"]
def package_changes(self, stateId, cityName):
self.col_data[1] = stateId
self.col_data[2] = cityName
def display_city_treeview(self, instance):
if len(instance.text) > 0:
if self.popup is None:
self.popup = TreeviewGroup()
#self.popup.filter(instance.text)
self.popup.open()
class SelectableButtonArea(RecycleDataViewBehavior, Button):
''' Add selection support to the Button '''
index = None
selected = BooleanProperty(False)
selectable = BooleanProperty(True)
rv_data_area = ObjectProperty(None)
start_point = NumericProperty(0)
def __init__(self, **kwargs):
super(SelectableButtonArea, self).__init__(**kwargs)
Clock.schedule_interval(self.update, .0005)
def update(self, *args):
self.text = self.rv_data_area[self.index][self.key]
def refresh_view_attrs(self, rv, index, data):
''' Catch and handle the view changes '''
self.index = index
return super(SelectableButtonArea, self).refresh_view_attrs(rv, index, data)
def on_touch_down(self, touch):
''' Add selection on touch down '''
if super(SelectableButtonArea, 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_area = rv.data
#print("selection changed to {0}".format(rv.data[1]))
def on_press(self):
popup = EditAreaPopup(self)
popup.open()
class RVAREA(BoxLayout):
data_items_area = ListProperty([])
col1 = ListProperty()
col2 = ListProperty()
col3 = ListProperty()
def __init__(self, **kwargs):
super(RVAREA, self).__init__(**kwargs)
self.get_areas()
def update(self):
self.col1 = [{'areaId': str(x[0]), 'cityId': str(x[1]), 'areaName': str(x[2]), 'key': 'areaId'} for x in self.data_items_area]
self.col2 = [{'areaId': str(x[0]), 'cityId': str(x[1]), 'areaName': str(x[2]), 'key': 'cityId'} for x in self.data_items_area]
self.col3 = [{'areaId': str(x[0]), 'cityId': str(x[1]), 'areaName': str(x[2]), 'key': 'areaName'} for x in self.data_items_area]
def get_areas(self):
rows = [(1, 'Amritsar', 'area1')]
i = 0
for row in rows:
self.data_items_area.append([row[0], row[1], row[2], i])
i += 1
print(self.data_items_area)
self.update()
class CustDrop(DropDown):
def __init__(self, **kwargs):
super(CustDrop, self).__init__(**kwargs)
self.select('')
class MainMenu(BoxLayout):
states_cities_or_areas = ObjectProperty()
rv = ObjectProperty(None)
dropdown = ObjectProperty(None)
#Define City Variable
rvcity = ObjectProperty(None)
#Area City Variable
rvarea = ObjectProperty(None)
def display_states(self):
self.dropdown.dismiss()
self.remove_widgets()
self.rv = RV()
self.states_cities_or_areas.add_widget(self.rv)
def display_cities(self):
self.dropdown.dismiss()
self.remove_widgets()
self.rvcity = RVCITY()
self.states_cities_or_areas.add_widget(self.rvcity)
def display_areas(self):
self.dropdown.dismiss()
self.remove_widgets()
self.rvarea = RVAREA()
self.states_cities_or_areas.add_widget(self.rvarea)
def remove_widgets(self):
self.states_cities_or_areas.clear_widgets()
class FactApp(App):
title = "test"
def build(self):
self.root = Builder.load_file('test.kv')
return MainMenu()
if __name__ == '__main__':
FactApp().run()
test.kv
#:kivy 1.10.0
#:import CoreImage kivy.core.image.Image
#:import os os
<EditStatePopup>:
title: "Update State"
size_hint: None, None
size: 500, 200
auto_dismiss: False
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
backgroun_color: 0, 0.517, 0.705, 1
spacing: 10, 10
Label:
text: "Id"
Label:
id: stateId
text: root.col_data[0]
Label:
text: "State Name"
TextInput:
id: stateName
text: root.col_data[1]
Label:
text: "State Code"
TextInput:
id: stateCode
text: root.col_data[2]
Button:
size_hint: 1, 1
text: "Ok"
on_release:
root.package_changes(stateName.text, stateCode.text)
app.root.update_states(root)
root.dismiss()
Button:
size_hint: 1, 1
text: "Cancel"
on_release: root.dismiss()
<TreeViewLabel>:
size_hint_y: None
height: 24
on_touch_down:
app.root.stateName.text = self.text
app.root.popup.dismiss()
<TreeviewGroup>:
id: treeview
treeview: treeview
title: "Select State"
size_hint: .3,.3
size: 800, 800
auto_dismiss: False
BoxLayout
orientation: "vertical"
ScrollView:
size_hint: 1, .9
BoxLayout:
size_hint_y: None
id: treeview
height: root.h
Button:
size_hint: 1, 0.1
text: "Close"
on_release: root.dismiss()
<SelectableButton>:
canvas.before:
Color:
rgba: (0, 0.517, 0.705, 1) if self.selected else (0, 0.517, 0.705, 1)
Rectangle:
pos: self.pos
size: self.size
<MyRV#RecycleView>:
viewclass: 'SelectableButton'
SelectableRecycleGridLayout:
cols: 1
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
<RV>:
BoxLayout:
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 3
Label:
size_hint_x: .1
text: "Id"
Label:
size_hint_x: .5
text: "State Name"
Label:
size_hint_x: .4
text: "State Code"
BoxLayout:
MyRV:
size_hint_x: .1
data: root.col1
MyRV:
size_hint_x: .5
data: root.col2
MyRV:
size_hint_x: .4
data: root.col3
<EditCityPopup>:
title: "Update State"
size_hint: None, None
size: 500, 400
auto_dismiss: False
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
backgroun_color: 0, 0.517, 0.705, 1
spacing: 10, 10
Label:
text: "City Id"
Label:
id: cityId
text: root.col_data[0]
Label:
text: "State Id"
TextInput:
id: stateId
text: root.col_data[1]
on_focus: root.display_states_treeview(self)
Label:
text: "city Name"
TextInput:
id: cityName
text: root.col_data[2]
Label:
text: "Short Name"
TextInput:
id: shortName
text: root.col_data[3]
Label:
text: "Pin Code"
TextInput:
id: pinCode
text: root.col_data[4]
Button:
size_hint: 1, 1
text: "Ok"
on_release:
root.package_changes(stateId.text, cityName.text, shortName.text, pinCode.text)
app.root.update_cities(root)
root.dismiss()
Button:
size_hint: 1, 1
text: "Cancel"
on_release: root.dismiss()
<MyRvCity#RecycleView>:
viewclass: 'SelectableButtonCity'
SelectableRecycleGridLayout:
cols: 1
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
<RVCITY>:
BoxLayout:
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y:None
height: 25
cols: 5
Label:
size_hint_x: .1
text: "City Id"
Label:
size_hint_x: .2
text: "State Name"
Label:
size_hint_x: .3
text: "City Name"
Label:
size_hint_x: .2
text: "Short Name"
Label:
size_hint_x: .2
text: "Pin Code"
BoxLayout:
MyRvCity:
size_hint_x: .1
data: root.col1
MyRvCity:
size_hint_x: .2
data: root.col2
MyRvCity:
size_hint_x: .3
data: root.col3
MyRvCity:
size_hint_x: .2
data: root.col4
MyRvCity:
size_hint_x: .2
data: root.col5
<EditAreaPopup>:
title: "Update State"
size_hint: None, None
size: 500, 400
auto_dismiss: False
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
backgroun_color: 0, 0.517, 0.705, 1
spacing: 10, 10
Label:
text: "City Id"
Label:
id: cityId
text: root.col_data[0]
Label:
text: "State Id"
TextInput:
id: stateId
text: root.col_data[1]
on_focus: root.display_states_treeview(self)
Label:
text: "city Name"
TextInput:
id: cityName
text: root.col_data[2]
Button:
size_hint: 1, 1
text: "Ok"
on_release:
root.package_changes(stateId.text, cityName.text, shortName.text, pinCode.text)
app.root.update_cities(root)
root.dismiss()
Button:
size_hint: 1, 1
text: "Cancel"
on_release: root.dismiss()
<MyRvArea#RecycleView>:
viewclass: 'SelectableButtonArea'
SelectableRecycleGridLayout:
cols: 1
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
<RVAREA>:
BoxLayout:
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 3
Label:
size_hint_x: .1
text: "Area Id"
Label:
size_hint_x: .5
text: "City Name"
Label:
size_hint_x: .4
text: "Area Name"
BoxLayout:
MyRvArea:
size_hint_x: .1
data: root.col1
MyRvArea:
size_hint_x: .5
data: root.col2
MyRvArea:
size_hint_x: .4
data: root.col3
<DropdownButton#Button>:
border: (0, 16, 0, 16)
text_size: self.size
valign: "middle"
padding_x: 5
size_hint_y: None
height: '30dp'
background_color: 90 , 90, 90, 90
color: 0, 0.517, 0.705, 1
<MenuButton#Button>:
text_size: self.size
valign: "middle"
padding_x: 5
size : (80,30)
size_hint : (None, None)
background_color: 90 , 90, 90, 90
background_normal: ''
color: 0, 0.517, 0.705, 1
border: (0, 10, 0, 0)
<MainMenu>:
states_cities_or_areas: states_cities_or_areas
dropdown: dropdown
BoxLayout:
orientation: 'vertical'
#spacing : 10
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
size_hint_y: 1
MenuButton:
id: btn
text: 'Test'
size : (60,30)
on_release: dropdown.open(self)
CustDrop:
id: dropdown
auto_width: False
width: 150
DropdownButton:
text: 'Test1'
size_hint_y: None
height: '32dp'
on_release: root.display_states()
DropdownButton:
text: 'Test2'
size_hint_y: None
height: '32dp'
on_release: root.display_cities()
DropdownButton:
text: 'Test3'
size_hint_y: None
height: '32dp'
on_release: root.display_areas()
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: (1,1,1)
Label:
size_hint_x: 45
BoxLayout:
id: states_cities_or_areas
size_hint_y: 10
Label:
size_hint_y: 1
Can anyone help me?
When i click on test then sub menu will be open.When i click on state then it look like good.But i click on city then distance increase between 'Test' and Row.
when i click on 'city' then show rows of city.when i click on any row then it looks Select state(treeview) show behind of 'update state'
I want it up on update state when anyone type anything in 'state Id'
i am using treeview in select state.how to add scrollbar in select state.when state increase then scroll will be good option
After update code I have a more error.
1. When i select state from select state then it's not put that string in state Name.Its showing error
File "/usr/share/kivy-examples/gst_fact/test.kv", line 50, in
app.root.stateName.text = self.text
AttributeError: 'MainMenu' object has no attribute 'stateName'
I want to when i click on anyone(state,city,area) then row show top position like Image_1.
It's because you have set the rules of your main menu in your kv to reserve the space for each box city, state and area. You can remove these rules and add only one box which I called states_cities_or_areas:
...
<MainMenu>:
states_cities_or_areas: states_cities_or_areas
dropdown: dropdown
BoxLayout:
orientation: 'vertical'
#spacing : 10
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
size_hint_y: 5
MenuButton:
id: btn
text: 'Test'
size : (60,30)
on_release: dropdown.open(self)
CustDrop:
id: dropdown
auto_width: False
width: 150
DropdownButton:
text: 'State'
size_hint_y: None
height: '32dp'
on_release: root.display_states()
DropdownButton:
text: 'City'
size_hint_y: None
height: '32dp'
on_release: root.display_cities()
DropdownButton:
text: 'Area'
size_hint_y: None
height: '32dp'
on_release: root.display_areas()
BoxLayout:
size_hint_y: 2.5
canvas.before:
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: (1,1,1)
Label:
size_hint_x: 45
BoxLayout:
id: states_cities_or_areas
size_hint_y: 89
Label:
size_hint_y: 1
...
then change some methods and attributes of the mainmenu in the .py:
...
class MainMenu(BoxLayout):
states_cities_or_areas = ObjectProperty()
rv = ObjectProperty(None)
dropdown = ObjectProperty(None)
#Define City Variable
rvcity = ObjectProperty(None)
#Area City Variable
rvarea = ObjectProperty(None)
def display_states(self):
self.dropdown.dismiss()
self.remove_widgets()
self.rv = RV()
self.states_cities_or_areas.add_widget(self.rv)
def display_cities(self):
self.dropdown.dismiss()
self.remove_widgets()
self.rvcity = RVCITY()
self.states_cities_or_areas.add_widget(self.rvcity)
def display_areas(self):
self.dropdown.dismiss()
self.remove_widgets()
self.rvarea = RVAREA()
self.states_cities_or_areas.add_widget(self.rvarea)
def remove_widgets(self):
self.states_cities_or_areas.clear_widgets()
...
I have noticed that the tiles of colums of city was not displayed, you can display it with this in the kv:
...
<RVCITY>:
BoxLayout:
orientation: "vertical"
GridLayout:
size_hint: 1, None
size_hint_y: None
height: 25
cols: 5
...
when i click on 'city' then show rows of city.when i click on any row then it looks Select state(treeview) show behind of 'update state' like image_4 I want it up on update state when anyone type anything in 'state Id' like image_5
It's because the StateId text input is already on_text before the the popup opens. I suggest you to replace on_text with on_focus:
...
<EditCityPopup>:
title: "Update State"
size_hint: None, None
size: 500, 400
auto_dismiss: False
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
backgroun_color: 0, 0.517, 0.705, 1
spacing: 10, 10
Label:
text: "City Id"
Label:
id: cityId
text: root.col_data[0]
Label:
text: "State Id"
TextInput:
id: stateId
text: root.col_data[1]
on_focus: root.display_states_treeview(self)
...
i am using treeview in select state.how to add scrollbar in select state.when state increase then scroll will be good option
You just have to put the treeview in a scrollview:
...
<TreeViewLabel>:
size_hint_y: None
height: 24
on_touch_down:
app.root.stateName.text = self.text
app.root.select_node(self)
app.root.popup.dismiss()
<TreeviewGroup>:
treeview: treeview
title: "Select State"
size_hint: .3,.3
auto_dismiss: False
BoxLayout
orientation: "vertical"
ScrollView:
size_hint: 1, .9
BoxLayout:
size_hint_y: None
id: treeview
height: root.h
Button:
size_hint: 1, 0.1
text: "Close"
on_release: root.dismiss()
and in the .py:
...
class TreeviewGroup(Popup):
treeview = ObjectProperty(None)
tv = ObjectProperty(None)
h = NumericProperty(0)
#ti = ObjectProperty()
def __init__(self, **kwargs):
super(TreeviewGroup, self).__init__(**kwargs)
self.tv = TreeView(root_options=dict(text=""),
hide_root=True,
indent_level=4)
for branch in tree:
populate_tree_view(self.tv, None, branch)
#self.remove_widgets()
self.treeview.add_widget(self.tv)
Clock.schedule_once(self.update, 1)
def remove_widgets(self):
for child in [child for child in self.treeview.children]:
self.treeview.remove_widget(child)
def update(self, *args):
self.h = len([child for child in self.tv.children]) * 24
Update
FOR THE 4TH POINT;
to pass the stateName to the other popup,keep the instance of the first popup when you create the 2nd:
...
class TreeviewGroup(Popup):
treeview = ObjectProperty(None)
tv = ObjectProperty(None)
h = NumericProperty(0)
#ti = ObjectProperty()
popup = ObjectProperty()
...
class EditCityPopup(Popup):
...
def display_states_treeview(self, instance):
if len(instance.text) > 0:
if self.popup is None:
self.popup = TreeviewGroup()
self.popup.popup = self
self.popup.open()
To reach the first popup in the kv make those changes:
in the .py:
...
class MyBoxLayout(BoxLayout):
rooot = ObjectProperty()
...
In the kv:
...
<TreeViewLabel>:
size_hint_y: None
height: 24
on_touch_down:
root.parent.parent.rooot.popup.col_data[1] = self.text
#app.root.select_node(self)
root.parent.parent.rooot.popup.popup.dismiss()
<TreeviewGroup>:
id: treeview
treeview: treeview
title: "Select State"
size_hint: .3,.3
size: 800, 800
auto_dismiss: False
BoxLayout
orientation: "vertical"
ScrollView:
size_hint: 1, .9
MyBoxLayout:
size_hint_y: None
id: treeview
height: root.h
rooot: root
...

when i click row then it shows error IndexError: list index out of range

menu.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.dropdown import DropDown
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
import sys
#Window.borderless = True
#Window.clearcolor = (0, 0.517, 0.705, 1)
Window.size = (900, 500)
#from easygui import msgbox
#db =lite.connect(':memory:')
con = lite.connect('test.db')
con.text_factory = str
cur = con.cursor()
class EditStatePopup(Popup):
obj = ObjectProperty(None)
start_point = NumericProperty(0)
max_table_cols = NumericProperty(0)
new_data = ListProperty([])
stateId = StringProperty("")
stateName = StringProperty("")
stateCode = StringProperty("")
def __init__(self, obj, **kwargs):
super(EditStatePopup, self).__init__(**kwargs)
self.obj = obj
self.start_point = obj.start_point
self.max_table_cols = obj.max_table_cols
self.stateId = obj.rv_data[obj.start_point]["text"]
self.stateName = obj.rv_data[obj.start_point + 1]["text"]
self.stateCode = obj.rv_data[obj.start_point + 2]["text"]
def package_changes(self, stateId, stateName, stateCode):
print(stateName)
self.new_data.append(stateId)
self.new_data.append(stateName)
self.new_data.append(stateCode)
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)
max_table_cols = NumericProperty(3)
data_items = ListProperty([])
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
#print("selection changed to {0}".format(rv.data[1]))
def on_press(self):
end_point = self.max_table_cols
rows = len(self.rv_data) # self.max_table_cols
#print(end_point) // 3
#print(rows) // 3
for row in range(rows):
cols = list(range(end_point))
#print(cols) // [0, 1, 2]
#print(self.index) //1
#print(self.max_table_cols)//3
if self.index in cols:
break
self.start_point += self.max_table_cols
end_point += self.max_table_cols
popup = EditStatePopup(self)
popup.open()
def update_states(self, stateId, stateName, stateCode):
cur.execute("UPDATE m_state SET state_name=?, state_code=? WHERE state_id=?",(stateName, stateCode, stateId))
con.commit()
class RV(BoxLayout):
data_items = ListProperty([])
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_states()
def get_states(self):
cur.execute("SELECT * FROM `m_state` order by state_id asc")
rows = cur.fetchall()
#print(rows)
# create data_items
rows = [(1, 'Test', '01'), (2, 'test2', '02'), (2, 'test2', '03')]
for row in rows:
for col in row:
self.data_items.append(col)
#print(col)
class CustDrop(DropDown):
def __init__(self, **kwargs):
super(CustDrop, self).__init__(**kwargs)
self.select('')
class MainMenu(BoxLayout):
states = ObjectProperty(None)
dropdown = ObjectProperty(None)
def display_states(self):
# rv = RV()
self.dropdown.dismiss()
self.states.add_widget(RV())
#return CustDrop()
class FactApp(App):
title = "Test"
def build(self):
self.root = Builder.load_file('m_ListState.kv')
return MainMenu()
if __name__ == '__main__':
FactApp().run()
m_ListState.kv
#:kivy 1.10.0
#:import CoreImage kivy.core.image.Image
#:import os os
<EditStatePopup>:
title: "Update State"
size_hint: None, None
size: 300, 300
auto_dismiss: False
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
Label:
text: "Id"
Label:
id: stateId
text: root.stateId
Label:
text: "Name"
TextInput:
id: stateName
text: root.stateName
Label:
text: "Code"
TextInput:
id: stateCode
text: root.stateCode
Button:
size_hint: 1, 0.4
text: "Cancel"
on_release: root.dismiss()
Button:
size_hint: 1, 0.4
text: "Ok"
on_release:
root.package_changes(stateId.text, stateName.text, stateCode.text)
#root.obj.update_states(root.start_point, root.max_table_cols, root.new_data)
root.obj.update_states(stateId.text, stateName.text, stateCode.text)
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: "Name"
Label:
text: "Code"
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
<DropdownButton#Button>:
border: (0, 16, 0, 16)
text_size: self.size
valign: "middle"
padding_x: 5
size_hint_y: None
height: '30dp'
background_color: 90 , 90, 90, 90
color: 0, 0.517, 0.705, 1
<MenuButton#Button>:
text_size: self.size
valign: "middle"
padding_x: 5
size : (80,30)
size_hint : (None, None)
background_color: 90 , 90, 90, 90
background_normal: ''
color: 0, 0.517, 0.705, 1
border: (0, 10, 0, 0)
<MainMenu>:
states: states
dropdown: dropdown
BoxLayout:
orientation: 'vertical'
#spacing : 10
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
size_hint_y: 1
MenuButton:
id: btn
text: 'View'
size : (60,30)
on_release: dropdown.open(self)
CustDrop:
id: dropdown
auto_width: False
width: 150
DropdownButton:
text: 'State'
size_hint_y: None
height: '32dp'
#on_release: dropdown3.open(self)
on_release: root.display_states()
DropdownButton:
text: 'City'
size_hint_y: None
height: '32dp'
#on_release: dropdown3.open(self)
on_release: root.display_city()
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: (1,1,1)
AsyncImage:
source: "add.jpg"
#on_release: os.system("python m_State.py")
Label:
size_hint_x: 22
BoxLayout:
id: states
size_hint_y: 9
Label:
size_hint_y: 9
Can anyone help for resolve some issue??
1. when i click on state (submenu of view) again and again then data repeats.How to avoid it.When i click on state then state list should be show and when i click on city then city list should be show.display_city() i have not written yet this for only example.
2. When i click on cancel two times then it shows error IndexError: list index out of range.
3.When i update state then it updated in database but does not change real time on screen.If i again run then shows updated data.
Please refer to the problems, solutions and example to solve your problems.
Columns Repeated
Problem
Each time you clicked View, widgets are dynamically added. If you clicked View twice, the columns are repeated twice.
Solution
You have to remove the widgets each time before adding them dynamically.
def display_states(self):
self.dropdown.dismiss()
self.remove_widgets()
self.rv = RV()
self.states.add_widget(self.rv)
def remove_widgets(self):
for child in [child for child in self.states.children]:
self.states.remove_widget(child)
IndexError
Problem
Whenever you clicked on each row of data, it invokes the on_press method. The self.start_point is initialized at the beginning when the class SelectableButton is instantiated.
Solution
Initialize self.start_point in the on_press method.
def on_press(self):
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 = EditStatePopup(self)
popup.open()
RecycleView Not Updated
Problem
In the method update_states, RecycleView's data update is missing.
Solution
Add the following to update RecycleView's data.
def update_states(self, obj):
# update data_items
# obj.start_point + 1 --- skip State_ID
for index in range(obj.start_point + 1, obj.start_point + MAX_TABLE_COLS):
self.rv.data_items[index] = obj.col_data[index - obj.start_point]
# update Database Table
cur.execute("UPDATE m_state SET State_Name=?, State_Code=? WHERE State_ID=?",
(obj.col_data[1], obj.col_data[2], obj.col_data[0]))
con.commit()
Example
m_ListState.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, ObjectProperty,NumericProperty
from kivy.lang import Builder
from kivy.uix.dropdown import DropDown
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
import sys
#Window.borderless = True
#Window.clearcolor = (0, 0.517, 0.705, 1)
Window.size = (900, 500)
#from easygui import msgbox
MAX_TABLE_COLS = 3
path = "/home/iam/dev/SQLite/sampleDB/StateCodesNamesDB/"
#db =lite.connect(':memory:')
# con = lite.connect('fact.db')
con = lite.connect(path + 'country.db')
con.text_factory = str
cur = con.cursor()
class EditStatePopup(Popup):
start_point = NumericProperty(0)
col_data = ListProperty(["?", "?", "?"])
def __init__(self, obj, **kwargs):
super(EditStatePopup, self).__init__(**kwargs)
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, stateName, stateCode):
self.col_data[1] = stateName
self.col_data[2] = stateCode
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)
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.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 = EditStatePopup(self)
popup.open()
class RV(BoxLayout):
data_items = ListProperty([])
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.get_states()
def get_states(self):
cur.execute("SELECT * FROM m_state order by State_ID asc")
rows = cur.fetchall()
# create data_items
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):
rv = ObjectProperty(None)
states = ObjectProperty(None)
dropdown = ObjectProperty(None)
def display_states(self):
self.dropdown.dismiss()
self.remove_widgets()
self.rv = RV()
self.states.add_widget(self.rv)
def remove_widgets(self):
for child in [child for child in self.states.children]:
self.states.remove_widget(child)
def update_states(self, obj):
# update data_items
# obj.start_point + 1 --- skip State_ID
for index in range(obj.start_point + 1, obj.start_point + MAX_TABLE_COLS):
self.rv.data_items[index] = obj.col_data[index - obj.start_point]
# update Database Table
cur.execute("UPDATE m_state SET State_Name=?, State_Code=? WHERE State_ID=?",
(obj.col_data[1], obj.col_data[2], obj.col_data[0]))
con.commit()
class FactApp(App):
title = "Test"
def build(self):
self.root = Builder.load_file('m_ListState.kv')
return MainMenu()
if __name__ == '__main__':
FactApp().run()
m_ListState.kv
#:kivy 1.10.0
#:import CoreImage kivy.core.image.Image
#:import os os
<EditStatePopup>:
title: "Update State"
size_hint: None, None
size: 300, 300
auto_dismiss: False
BoxLayout:
orientation: "vertical"
GridLayout:
cols: 2
Label:
text: "Id"
Label:
id: stateId
text: root.col_data[0]
Label:
text: "Name"
TextInput:
id: stateName
text: root.col_data[1]
Label:
text: "Code"
TextInput:
id: stateCode
text: root.col_data[2]
Button:
size_hint: 1, 0.4
text: "Cancel"
on_release: root.dismiss()
Button:
size_hint: 1, 0.4
text: "Ok"
on_release:
root.package_changes(stateName.text, stateCode.text)
app.root.update_states(root)
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: "Name"
Label:
text: "Code"
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
<DropdownButton#Button>:
border: (0, 16, 0, 16)
text_size: self.size
valign: "middle"
padding_x: 5
size_hint_y: None
height: '30dp'
background_color: 90 , 90, 90, 90
color: 0, 0.517, 0.705, 1
<MenuButton#Button>:
text_size: self.size
valign: "middle"
padding_x: 5
size : (80,30)
size_hint : (None, None)
background_color: 90 , 90, 90, 90
background_normal: ''
color: 0, 0.517, 0.705, 1
border: (0, 10, 0, 0)
<MainMenu>:
states: states
dropdown: dropdown
BoxLayout:
orientation: 'vertical'
#spacing : 10
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
size_hint_y: 1
MenuButton:
id: btn
text: 'View'
size : (60,30)
on_release: dropdown.open(self)
CustDrop:
id: dropdown
auto_width: False
width: 150
DropdownButton:
text: 'State'
size_hint_y: None
height: '32dp'
#on_release: dropdown3.open(self)
on_release: root.display_states()
DropdownButton:
text: 'City'
size_hint_y: None
height: '32dp'
#on_release: dropdown3.open(self)
on_release: root.display_city()
BoxLayout:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
Color:
rgb: (1,1,1)
AsyncImage:
source: "clipboard.jpeg" # "gst_image/add.jpg"
#on_release: os.system("python m_State.py")
Label:
size_hint_x: 22
BoxLayout:
id: states
size_hint_y: 9
Label:
size_hint_y: 9
Output

Categories