I'm trying to optimize the chat bubble mechanism, but still can't figure out the values that I need to set for my texture_size.
As you can see in the picture below, the first chat bubble seems to be okay, but when the second one has more words and reach the width limit then down the line, the label's texture_size[0] will be replaced as its max-width (the orange one) which means the box containing the label (the green one) that has its size attach to the label's texture_size will have its width set to the max-width and won't be able to track the label's texture_size anymore and cause some gaps as I showed below (the red one).
The gaps should be removed like this:
Here's a small app that I convert from the issue code.
.py file
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import ListProperty,BooleanProperty, StringProperty
from datetime import datetime
class HistoryBox(BoxLayout):
chat_logs = ListProperty()
def send(self, text):
now = datetime.now()
current_time = now.strftime("%H:%M")
self.create_chatbubble(text,True,current_time)
self.ids.field.text = ""
def create_chatbubble(self,message,send_by_user,time):
self.chat_logs.append(
{
"text":message,
"send_by_user": send_by_user,
"time": time,
}
)
class ChatBubble(BoxLayout):
send_by_user = BooleanProperty()
text = StringProperty()
time = StringProperty()
class App(App):
def build(self):
self.root = Builder.load_file("my.kv")
if __name__ == "__main__":
App().run()
.kv file
HistoryBox:
<HistoryBox>:
orientation: "vertical"
RecycleView:
data: root.chat_logs
viewclass: "ChatBubble"
RecycleBoxLayout:
id: box
padding: dp(10)
spacing: dp(15)
orientation: "vertical"
height: self.minimum_size[1]
default_size_hint: 1, None
default_size: None, None
TextInput:
id: field
hint_text: "Write your message"
multiline: False
focus: True
padding: dp(7)
size_hint_y: .6
size_hint_max_y: (len(self._lines)+1)*self.line_height
on_text_validate:
root.send(self.text)
<ChatBubble>:
id: chtbld
md_bg_color: [0, 0, 0, 0]
size_hint_y: None
height: wrapped.height
pos_hint: {'right': 1} if chtbld.send_by_user == True else {'x': 0}
#adaptive_height: True
width: root.width
padding: [10, 0, 10, 0]
orientation: 'vertical'
BoxLayout:
id: wrapped
height: msg_content.height + timed.height + 10
width: msg_content.width + wid1.width + wid2.width
size_hint: None, None
pos_hint: {'right': 1} if chtbld.send_by_user == True else {'x': 0}
canvas.before:
Color:
rgba: 1,1,1,1
RoundedRectangle:
pos: self.pos
size: self.size
radius: [10, 10, (1, -5), 10] if self.pos_hint == {'right': 1} else [10, 10, 10, (1, -5)]
Spacer:
id: wid1
BoxLayout:
orientation: 'vertical'
height: msg_content.height + tc.height + wid3.height
width: msg_content.width
Label:
id: msg_content
text: root.text
width: tc.width if self.texture_size[0] < tc.width else self.texture_size[0]
height: self.texture_size[1]
size_hint_y: None
text_size: chtbld.width-dp(100) if self.width >= chtbld.width-dp(100) else None,None
halign: 'left'
color: 0, 0, 0, 1
BoxLayout:
id: tc
size_hint: None, None
height: timed.height
width: timed.width + 3
pos_hint: {'right': 1}
spacing: 3
Label:
id: timed
text: root.time
size_hint: None, None
size: self.texture_size
font_size: 9
bold: True
text_size: None,None
color: [.8, .8, .8, 1]
Spacer:
id: wid3
height: 5
Spacer:
id: wid2
<Spacer#Widget>:
id: wid
width: 5
size_hint: None, None
Just type anything like "welcomeeeeee toooooooooooooo" then minimize the window till the sentence down the line and you will notice the problem. Any help or advice would be helpful.
Related
I have managed to get the size of a box layout to change based on the corresponding Label height, however, it doesn't line up perfectly and I cannot figure out why.
I have looked at adding offsets but have had no luck since it ended up making the issue worse
Thank you for any help
MainInterface:
<MainInterface#BoxLayout>:
orientation: "vertical"
Label:
#font_name: "Nunito-Black.ttf"
text: "T R U T H"
size_hint: 1, 0.1
GridLayout:
size_hint: 1, 0.12
cols: 4
Button:
text: "Menu1"
Button:
text: "Menu2"
Button:
text: "Menu3"
Button:
text: "Menu4"
PageLayout:
border: "20dp"
swipe_threshold: 0.2
RecycleView:
viewclass: 'PostGrid'
scroll_y: 1
id: rv
data: app.posts
RecycleBoxLayout:
id: box
default_size: None, None
default_size_hint: 1, None
size_hint_y: None
padding: ["10dp", "16dp"]
spacing: "8dp"
height: self.minimum_height
orientation: 'vertical'
key_size: '_size'
BoxLayout:
orientation: "vertical"
Button:
text: "peni"
Button:
text: "tag # will J"
Button:
text: "Input"
<PostGrid#BoxLayout>:
message_id: -1
orientation: "horizontal"
text: ''
spacing: "10dp"
#size_hint: self.width, None
_size: 0, 74
size: 0, 74
text_size: None, None
BoxLayout:
orientation: "vertical"
spacing: "10dp"
size_hint: .1, 1
size: self.size
Button:
text: "UP"
font_size: "5dp"
size_hint: 1, 0.2
Button:
text: "DOWN"
font_size: "5dp"
size_hint: 1, 0.2
Label:
text: "test"
font_size: "5dp"
size_hint: 1, 0.6
Label:
text: root.text
padding: 5, 5
size_hint: .9, 1
#size: self.texture_size
height: self.texture_size[1]
text_size: self.width, None
color: 0,0,0,1
#text_size: self.width, None
#size_hint: None, 1
#size: self.texture_size
#font_name: "Nunito-Bold.ttf"
#font_size: "12dp"
multiline: True
#size: 1, root.min_height
on_texture_size:
app.update_message_size(
root.message_id,
self.texture_size,
root.width)
pos: self.pos
canvas.before:
Color:
rgba: (0.8, 0.8, 0.8, 1)
RoundedRectangle:
size: self.texture_size
radius: [5, 5, 5, 5]
pos: self.x, self.y
canvas:
Color:
rgba:0,0.9,0.9,1
Line:
width:0.8
rounded_rectangle:(self.x,self.y,self.width,self.height, 5)
from kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.properties import ListProperty
from kivy.animation import Animation
from kivy.metrics import dp
class TruthApp(App):
posts = ListProperty([{'message_id':0, 'text':"testskjhfjksdhfkjshfjshfjkhskjdfhskjdhfkjshfdkjhsjkdfhskjhdfkjshdfjkhzxczxczxczxcxzczxcxsjkdfhjksdhfkjshkjdfhksjdhfjkshdfjkhsdkjhfkjshdfjkshkjfhskjhfkjshfjkshdkjfhskjhfjshfkjshdfjkshdjkfhskjhfkjshfjksdhjfhsjkdhfjkhsdkjfhskjhfjk\ngdgdgd\ndgdgdg\ndgdgdg\ndggdgd",'_size':[0,0] }, {'message_id':1, 'text':"testskjhfjksdhfkjshfjshfjkhskjdfhskjdhfkjshfdkjhsjkdfhskjhjfhskjhfjk,'_size':[0,0]"}])
def update_message_size(self, message_id, texture_size, max_width):
#print(self.posts)
#print("Here")
self.posts[message_id] = {**self.posts[message_id], '_size':[0, texture_size[1]]}
if __name__ == '__main__':
TruthApp().run()
^ Image showing how the code above runs
The problem is in the viewclass of RecycleView (i.e. PostGrid). You set its heightas such it could not accomodate its children which is supposed to be the minimum height that will place all its children.
Now that's exactly the attr. minimum_height does. With this being applied you also don't need default_size: None, None (especially the height attr.)
With this and other modifications your .kv file should now look like,
MainInterface:
<MainInterface#BoxLayout>:
orientation: "vertical"
Label:
#font_name: "Nunito-Black.ttf"
text: "T R U T H"
size_hint: 1, 0.1
GridLayout:
size_hint: 1, 0.12
cols: 4
Button:
text: "Menu1"
Button:
text: "Menu2"
Button:
text: "Menu3"
Button:
text: "Menu4"
PageLayout:
border: "20dp"
swipe_threshold: 0.2
RecycleView:
viewclass: 'PostGrid'
scroll_y: 1
id: rv
data: app.posts
RecycleBoxLayout:
id: box
default_size_hint: 1, None
size_hint_y: None
padding: ["10dp", "16dp"]
spacing: "8dp"
height: self.minimum_height
orientation: 'vertical'
key_size: '_size'
BoxLayout:
orientation: "vertical"
Button:
text: "peni"
Button:
text: "tag # will J"
Button:
text: "Input"
<PostGrid#BoxLayout>:
message_id: -1
orientation: "horizontal"
text: ''
spacing: "10dp"
size_hint_y: None
#_size: 0, 74
height: self.minimum_height
text_size: None, None
BoxLayout:
orientation: "vertical"
spacing: "10dp"
size_hint: .1, 1
Button:
text: "UP"
font_size: "5dp"
size_hint: 1, 0.2
Button:
text: "DOWN"
font_size: "5dp"
size_hint: 1, 0.2
Label:
text: "test"
font_size: "5dp"
size_hint: 1, 0.6
Label:
text: root.text
padding: 5, 5
#size_hint: .9, 1
#size: self.texture_size
size_hint_y: None
height: self.texture_size[1]
text_size: self.width, None
color: 0,0,0,1
#text_size: self.width, None
#size_hint: None, 1
#size: self.texture_size
#font_name: "Nunito-Bold.ttf"
#font_size: "12dp"
multiline: True
#size: 1, root.min_height
on_texture_size:
app.update_message_size(
root.message_id,
self.texture_size,
root.width)
pos: self.pos
canvas.before:
Color:
rgba: (0.8, 0.8, 0.8, 1)
RoundedRectangle:
size: self.texture_size
radius: [5, 5, 5, 5]
pos: self.x, self.y
canvas:
Color:
rgba:0,0.9,0.9,1
Line:
width:0.8
rounded_rectangle:(self.x,self.y,self.width,self.height, 5)
I am getting this error when I run my program and have no idea what it means and I've been commenting out everything one at a time and it hasn't fixed it
ph = item.get('pos_hint', ph)
I have added the code I am running below, it is my original program that I have re-formatted to allow for the change in size of a BoxLayout inside of a RecycleView, which was taken from a GitHub kivy example
MainInterface:
<MainInterface#BoxLayout>:
orientation: "vertical"
Label:
#font_name: "Nunito-Black.ttf"
text: "T R U T H"
size_hint: 1, 0.1
GridLayout:
size_hint: 1, 0.12
cols: 4
Button:
text: "Menu1"
Button:
text: "Menu2"
Button:
text: "Menu3"
Button:
text: "Menu4"
PageLayout:
border: "20dp"
swipe_threshold: 0.2
RecycleView:
viewclass: 'PostGrid'
scroll_y: 1
id: rv
data: app.posts
RecycleBoxLayout:
id: box
default_size: None, None
default_size_hint: 1, None
size_hint_y: None
padding: ["10dp", "16dp"]
spacing: "8dp"
height: self.minimum_height
orientation: 'vertical'
key_size: '_size'
BoxLayout:
orientation: "vertical"
Button:
text: "peni"
Button:
text: "tag # will J"
Button:
text: "Input"
<PostGrid#BoxLayout>:
message_id: -1
orientation: "horizontal"
text: ''
size_hint_y: None
_size: 0, 0
size: self._size
BoxLayout:
orientation: "vertical"
#size_hint: .1, 1
Button:
text: "UP"
size_hint: 1, 0.3
Button:
text: "DOWN"
size_hint: 1, 0.3
Label:
text: "test"
size_hint: 1, 0.4
Label:
text: root.text
color: 0,0,0,1
#text_size: self.width, None
size_hint: None, 1
size: self.texture_size
#font_name: "Nunito-Bold.ttf"
font_size: "12dp"
smultiline: True
#size: 1, root.min_height
on_texture_size:
app.update_message_size(
root.message_id,
self.texture_size,
root.width)
canvas.before:
Color:
rgba: (0.8, 0.8, 0.8, 1)
RoundedRectangle:
size: self.texture_size
radius: [5, 5, 5, 5]
pos: self.pos
canvas:
Color:
rgba:0,0.9,0.9,1
Line:
width:0.8
rounded_rectangle:(self.x,self.y,self.width,self.height, 5)
rom kivy.app import App
from kivy.lang import Builder
from kivy.clock import Clock
from kivy.properties import ListProperty
from kivy.animation import Animation
from kivy.metrics import dp
class TruthApp(App):
posts = ListProperty({'message_id':0, 'text':"test", 'text_size': [None, None], 'side': "left"})
def update_message_size(self, message_id, texture_size, max_width):
# when the label is updated, we want to make sure the displayed size is
# proper
if max_width == 0:
return
one_line = dp(20) # a bit of hack, YMMV
# if the texture is too big, limit its size
if texture_size[0] >= max_width * 2 / 3:
self.messages[message_id] = {
**self.messages[message_id],
'text_size': (max_width * 2 / 3, None),
}
# if it was limited, but is now too small to be limited, raise the limit
elif texture_size[0] < max_width * 2 / 3 and \
texture_size[1] > one_line:
self.messages[message_id] = {
**self.messages[message_id],
'text_size': (max_width * 2 / 3, None),
'_size': texture_size,
}
# just set the size
else:
self.messages[message_id] = {
**self.messages[message_id],
'_size': texture_size,
}
if __name__ == '__main__':
TruthApp().run()
Thanks for any help you can provide
I would like to add a rounded rectangle behind each row of widgets containing 3 buttons and two labels all horizontally layout. Each group contents are added dynamically through the input_text and '+' button on the bottom. I have all the major parts working but I can't get the rounded rectangle graphic.
Here is what I've got so far:
I was hoping to create something like this:
Please let me know where I went wrong and how to fix it I'm pretty new in Kivy so I'm just learning.
Thanks.
class Trackers(Screen):
storage = {}
path = ''
def on_pre_enter(self):
self.path = App.get_running_app().user_data_dir + '/'
self.loadData()
for tracker, num in self.storage.items():
self.ids.track.add_widget(Tracker(text=tracker, number=num, data=self.storage))
def addWidget(self):
text_input = self.ids.text_input.text
num = '0'
if text_input not in self.storage.keys():
self.ids.track.add_widget(Tracker(text=text_input, number=num, data=self.storage))
self.storage[text_input] = '0'
self.ids.text_input.text = ''
self.saveData()
class Tracker(BoxLayout):
def __init__(self, text='', number='', data={}, **kwargs):
super().__init__(**kwargs)
self.ids.label.text = text
self.ids.count_add.text = number
class Pess(App):
def build(self):
Config.set('graphics', 'width', '600')
Config.set('graphics', 'height', '800')
from kivy.core.window import Window
Window.clearcolor = get_color_from_hex('#262829')
return ScreenGenerator()
##### --> .kv file
<Trackers>:
BoxLayout:
orientation: 'vertical'
ActionBar:
height: 45
size_hint_y: None
background_image: ''
background_color: rgba('#0B3242')
ActionView:
ActionPrevious:
title: '[b]TRACKERS[/b]'
font_size: 21
color: rgba('#AFB7BA')
markup: True
on_release: app.root.current = 'menu'
ActionButton:
text: 'SEND'
color: rgba('#AFB7BA')
on_release: root.send()
ScrollView:
BoxLayout:
id: track
orientation: 'vertical'
font_size: 15
size_hint_y: None
height: self.minimum_height
BoxLayout:
size_hint_y: None
height: 45
TextInput:
id: text_input
hint_text: 'Add Trackers'
multiline: False
Button:
text: '+'
size_hint_x: None
width: 60
on_release: root.addWidget()
background_color: rgba('#1D7332')
<Tracker>:
count_add: count_add
size_hint_y: None
height: 45
padding: 4
Button:
text: '[b]X[/b]'
markup: True
size_hint_x: None
width: 60
on_release: app.root.get_screen('track').delete_storage(root)
Label:
id: label
font_size: 20
Label:
id: count_add
font_size: 20
text: '0'
Button:
text: '[b]-[/b]'
markup: True
size_hint_x: None
width: 60
on_release: app.root.get_screen('track').subtract_num(root)
Button:
text: '[b]+[/b]'
markup: True
size_hint_x: None
width: 60
on_release: app.root.get_screen('track').add_num(root)
In your 'kv' file, you can add graphics to the Canvas of your Tracker like this:
<Tracker>:
count_add: count_add
size_hint_y: None
height: 45
padding: 20, 4, 20, 4 # to keep widgets a bit away from the sides
canvas.before: # use before to keep this under any widgets
Color:
rgba: 1, 0, 0, 1 # any color you want
Rectangle:
pos: self.pos[0] + self.height/2, self.pos[1]
size: self.size[0] - self.height, self.height
Ellipse:
pos: self.pos[0], self.pos[1]
size: self.height, self.height
Ellipse:
pos: self.pos[0] + self.width - self.height, self.pos[1]
size: self.height, self.height
You might want to add some spacing to your track id BoxLayout so that the Tracker widgets don't appear connected.
Here is the entire version of your code that I ran. There are a few lines commented out, since you did not provide all the code:
from kivy.config import Config
from kivy.app import App
from kivy.lang import Builder
from kivy.properties import get_color_from_hex
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.screenmanager import Screen, ScreenManager
class Trackers(Screen):
storage = {}
path = ''
def on_pre_enter(self):
self.path = App.get_running_app().user_data_dir + '/'
#self.loadData()
for tracker, num in self.storage.items():
self.ids.track.add_widget(Tracker(text=tracker, number=num, data=self.storage))
def addWidget(self):
text_input = self.ids.text_input.text
num = '0'
if text_input not in self.storage.keys():
self.ids.track.add_widget(Tracker(text=text_input, number=num, data=self.storage))
self.storage[text_input] = '0'
self.ids.text_input.text = ''
#self.saveData()
class Tracker(BoxLayout):
def __init__(self, text='', number='', data={}, **kwargs):
super().__init__(**kwargs)
self.ids.label.text = text
self.ids.count_add.text = number
Builder.load_string('''
<Trackers>:
BoxLayout:
orientation: 'vertical'
ActionBar:
height: 45
size_hint_y: None
background_image: ''
background_color: rgba('#0B3242')
ActionView:
ActionPrevious:
title: '[b]TRACKERS[/b]'
font_size: 21
color: rgba('#AFB7BA')
markup: True
on_release: app.root.current = 'menu'
ActionButton:
text: 'SEND'
color: rgba('#AFB7BA')
on_release: root.send()
ScrollView:
BoxLayout:
id: track
orientation: 'vertical'
spacing: 5
font_size: 15
size_hint_y: None
height: self.minimum_height
BoxLayout:
size_hint_y: None
height: 45
TextInput:
id: text_input
hint_text: 'Add Trackers'
multiline: False
Button:
text: '+'
size_hint_x: None
width: 60
on_release: root.addWidget()
background_color: rgba('#1D7332')
<Tracker>:
count_add: count_add
size_hint_y: None
height: 45
padding: 20, 4, 20, 4
canvas.before:
Color:
rgba: 1, 0, 0, 1
Rectangle:
pos: self.pos[0] + self.height/2, self.pos[1]
size: self.size[0] - self.height, self.height
Ellipse:
pos: self.pos[0], self.pos[1]
size: self.height, self.height
Ellipse:
pos: self.pos[0] + self.width - self.height, self.pos[1]
size: self.height, self.height
Button:
text: '[b]X[/b]'
markup: True
size_hint_x: None
width: 60
on_release: app.root.get_screen('track').delete_storage(root)
Label:
id: label
font_size: 20
Label:
id: count_add
font_size: 20
text: '0'
Button:
text: '[b]-[/b]'
markup: True
size_hint_x: None
width: 60
on_release: app.root.get_screen('track').subtract_num(root)
Button:
text: '[b]+[/b]'
markup: True
size_hint_x: None
width: 60
on_release: app.root.get_screen('track').add_num(root)
''')
class Pess(App):
def build(self):
Config.set('graphics', 'width', '600')
Config.set('graphics', 'height', '800')
from kivy.core.window import Window
Window.clearcolor = get_color_from_hex('#262829')
# Don't have `ScreenGenerator` so just set up `ScreenManager`
sm = ScreenManager()
sm.add_widget(Trackers(name='trackers'))
return sm
#return ScreenGenerator()
Pess().run()
So the text is blurring when animating its scale to 1.1 using an animation in kivy. I'm sure it's because the font size is static this entire time and is being stretched as a result.
Is there a way to increase scale size of text using an animation while keeping its clarity?
I've also noticed a strange issue where when they enlarge, all the other widgets above are pushed as well. I'm trying to localize it. This is my .kv file.
Builder.load_string("""
#:import F kivy.factory.Factory
#:import HoverButton BasicUI.HoverButton
#:import changeTypeToId Database.changeTypeToId
#:import utils kivy.utils
<ChangeButton#HoverButton>:
background_color: 0, 0, 0, 1
markup: True
font_size: 32
size_hint: None, None
width: self.texture_size[0] + 5
height: self.texture_size[1] + 5 if self.texture_size[1] != 0 else 46
canvas.before:
PushMatrix:
Scale:
origin: self.x + 0.5*self.width, self.y + 0.5*self.height
x: self.scale
y: self.scale
canvas.after:
PopMatrix:
<SmallChangeButton#HoverButton>:
markup: True
font_size: 16
size_hint: None, None
width: self.texture_size[0] + 5
height: self.texture_size[1] + 5 if self.texture_size[1] != 0 else 24
background_color: 0, 0, 0, 1
on_enter: self.setFontSize(20)
on_leave: self.setFontSize(16)
<ChooseChangeScreen>:
FloatLayout:
Label:
x: 20
pos_hint: {"top": 1}
font_size: 40
size_hint: None, None
width: self.texture_size[0] + 5
font_name: "TitleFont"
text: "JARVIS"
Label:
font_size: 16
pos_hint: {"top": 1, "right": .98}
size_hint: None, None
width: self.texture_size[0] + 5
height: self.texture_size[1] + 50
color: utils.get_color_from_hex('#05eeff')
markup: True
text: "[b]Xari[/b]"
BoxLayout:
x: 20
pos_hint: { "top": .5}
size_hint_x: .5
size_hint_y: None
orientation: "vertical"
spacing: 3
ChangeButton:
text: "[i][b]ADD CHANGES[/i][/b]"
on_press:
root.manager.transition.direction = "right"
root.manager.transition.duration = .5
root.manager.current = 'MainMenu'
ChangeButton:
text: "[b][i]MODIFY CHANGES[/i][/b]"
SmallChangeButton:
SmallChangeButton:
""")
The animations are
def on_enter(self, *args):
self.initial_font = self.font_size
anim = Animation(font_size=self.font_size * 1.2, duration=.07)
anim.start(self)
def on_leave(self, *args):
anim = Animation(font_size=self.initial_font, duration=.07)
anim.start(self)
I have two file test.py and test.kv .
i run test.py then shows show button.
When i click on show button then def abc call.Can someone tell me how to show array in dynamic label and value(Item1=5000.Item2=1000).
Item1 5000
Item2 1000
I am using array
arr = ({'Item1': 5000},{'Item2': 1000})
test.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.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty
Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (600, 600)
class Invoice(Screen):
def __init__(self, **kwargs):
super(Invoice, self).__init__(**kwargs)
def abc(self):
#fetching from database
arr = ({'Item1': 5000},{'Item2': 1000})
print(arr)
class Test(App):
def build(self):
self.root = Builder.load_file('test.kv')
return self.root
if __name__ == '__main__':
Test().run()
test.kv
<Button#Button>:
font_size: 15
font_name: 'Verdana'
size_hint_y:None
height: 30
<Label#Label>:
font_size: 15
font_name: 'Verdana'
size_hint_y:None
height: 30
Invoice:
BoxLayout:
orientation: "vertical"
padding : 15, 15
BoxLayout:
orientation: "vertical"
padding : 5, 5
size_hint: .6, None
pos_hint: {'x': .18,}
BoxLayout:
orientation: "horizontal"
padding : 5, 5
spacing: 10, 10
size: 800, 40
size_hint: 1, None
Button:
text: "Show"
size_hint_x: .05
spacing_x: 30
on_press:root.abc()
BoxLayout:
orientation: "horizontal"
size_hint: 1, 1
BoxLayout:
orientation: "vertical"
size_hint: .5, 1
padding : 0, 15
spacing: 10, 10
size: 500, 30
Button:
text: "Invoice"
text_size: self.size
halign: 'center'
valign: 'middle'
GridLayout:
cols: 2
#orientation: "horizontal"
padding : 5, 0
spacing: 10, 0
#size: 500, 30
size_hint: 1, 1
pos: self.pos
size: self.size
Label:
size_hint_x: .35
text: "Item1"
text_size: self.size
halign: 'left'
valign: 'middle'
canvas.before:
Color:
rgb: .6, .6, .6
Rectangle:
pos: self.pos
size: self.size
Label:
size_hint_x: .15
text: "5000"
text_size: self.size
halign: 'right'
valign: 'middle'
canvas.before:
Color:
rgb: .6, .6, .6
Rectangle:
pos: self.pos
size: self.size
In your abc() method you can create labels and add them to your layout. In order to do that, I made a few change to your code. I added an id to your GridLayout and changed your custom label class to MyLabel and added it to the py file, so that I could create them in Python. Here is the modified Python file:
from kivy.uix.label import Label
from kivy.uix.screenmanager import Screen
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (600, 600)
class MyLabel(Label):
pass
class Invoice(Screen):
def __init__(self, **kwargs):
super(Invoice, self).__init__(**kwargs)
def abc(self):
#fetching from database
arr = ({'Item1': 5000},{'Item2': 1000})
layout = self.ids['invoices']
for invoice in arr:
for key,val in invoice.items():
lab1 = MyLabel(text=str(key),size_hint_x=.35, halign='left' )
lab2 = MyLabel(text=str(val),size_hint_x=.15, halign='right' )
layout.add_widget(lab1)
layout.add_widget(lab2)
class Test(App):
def build(self):
self.root = Builder.load_file('test.kv')
return self.root
And changes to the kv file included changing Label to MyLabel, moving as much as possible to the MyLabel class, and removing your example labels:
<Button#Button>:
font_size: 15
font_name: 'Verdana'
size_hint_y:None
height: 30
<MyLabel>:
font_size: 15
font_name: 'Verdana'
size_hint_y:None
height: 30
text_size: self.size
valign: 'middle'
canvas.before:
Color:
rgb: .6, .6, .6
Rectangle:
pos: self.pos
size: self.size
Invoice:
BoxLayout:
orientation: "vertical"
padding : 15, 15
BoxLayout:
orientation: "vertical"
padding : 5, 5
size_hint: .6, None
pos_hint: {'x': .18,}
BoxLayout:
orientation: "horizontal"
padding : 5, 5
spacing: 10, 10
size: 800, 40
size_hint: 1, None
Button:
text: "Show"
size_hint_x: .05
spacing_x: 30
on_press:root.abc()
BoxLayout:
orientation: "horizontal"
size_hint: 1, 1
BoxLayout:
orientation: "vertical"
size_hint: .5, 1
padding : 0, 15
spacing: 10, 10
size: 500, 30
Button:
text: "Invoice"
text_size: self.size
halign: 'center'
valign: 'middle'
GridLayout:
id: invoices
cols: 2
#orientation: "horizontal"
padding : 5, 0
spacing: 10, 0
#size: 500, 30
size_hint: 1, 1
pos: self.pos
size: self.size
Although the option to iterate over the data and generate the widget dynamically is an option, the truth is that it is unbeatable in the long term. If you have structured information it is appropriate to use a design pattern and kivy offers to use a RecycleView for these cases, this implements the MVC pattern, so we just need to pass the data and establish a view where an appropriate adapter can be provided.
In your case it is enough to design a widget that is what is shown in each row:
<Item#GridLayout>:
cols: 2
text: "" # new property
value: 0 # new property
padding : 5, 0
spacing: 10, 0
Label:
size_hint_x: .35
text: root.text
halign: 'left'
valign: 'middle'
canvas.before:
Color:
rgb: .6, .6, .6
Rectangle:
pos: self.pos
size: self.size
Label:
size_hint_x: .15
text: str(root.value)
halign: 'right'
valign: 'middle'
canvas.before:
Color:
rgb: .6, .6, .6
Rectangle:
pos: self.pos
size: self.size
And then replace the GridLayout with the RecycleView:
RecycleView:
id: rv
viewclass: 'Item'
RecycleBoxLayout:
default_size: None, dp(30)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
And in the event of the button assign the data, in this case you must convert your data to a list of dictionaries where the fields will be the text and value attribute of Item:
def convert_data(data):
l = []
for item in data:
for key, value in item.items():
l.append({'text': key, 'value': value})
return l
class Invoice(Screen):
def abc(self):
#fetching from database
arr = ({'Item1': 5000},{'Item2': 1000})
# convert to [{'text': 'Item1', 'value': 5000}, {'text': 'Item2', 'value': 1000}]
self.rv.data = convert_data(arr)
Complete Code:
main.py
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import Screen
def convert_data(data):
l = []
for item in data:
for key, value in item.items():
l.append({'text': key, 'value': value})
return l
class Invoice(Screen):
def abc(self):
#fetching from database
arr = ({'Item1': 5000},{'Item2': 1000})
# convert to [{'text': 'Item1', 'value': 5000}, {'text': 'Item2', 'value': 1000}]
self.rv.data = convert_data(arr)
class MyApp(App):
def build(self):
return Builder.load_file('test.kv')
if __name__ == '__main__':
MyApp().run()
test.kv
<Button#Button>:
font_size: 15
size_hint_y:None
height: 30
<Label#Label>:
font_size: 15
size_hint_y:None
height: 30
<Item#GridLayout>:
cols: 2
text: ""
value: 0
padding : 5, 0
spacing: 10, 0
Label:
size_hint_x: .35
text: root.text
halign: 'left'
valign: 'middle'
canvas.before:
Color:
rgb: .6, .6, .6
Rectangle:
pos: self.pos
size: self.size
Label:
size_hint_x: .15
text: str(root.value)
halign: 'right'
valign: 'middle'
canvas.before:
Color:
rgb: .6, .6, .6
Rectangle:
pos: self.pos
size: self.size
Invoice:
rv: rv
BoxLayout:
orientation: "vertical"
padding : 15, 15
BoxLayout:
orientation: "vertical"
padding : 5, 5
size_hint: .6, None
pos_hint: {'x': .18,}
BoxLayout:
orientation: "horizontal"
padding : 5, 5
spacing: 10, 10
size: 800, 40
size_hint: 1, None
Button:
text: "Show"
size_hint_x: .05
spacing_x: 30
on_press:root.abc()
BoxLayout:
orientation: "horizontal"
size_hint: 1, 1
BoxLayout:
orientation: "vertical"
size_hint: .5, 1
padding : 0, 15
spacing: 10, 10
size: 500, 30
Button:
text: "Invoice"
text_size: self.size
halign: 'center'
valign: 'middle'
BoxLayout:
RecycleView:
id: rv
viewclass: 'Item'
RecycleBoxLayout:
default_size: None, dp(30)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'