Adjustable textinput in kivy scrollview - python-3.x

I am new to Kivy. I would like multiple textInputs to be displayed properly inside the Kivy scrollView dynamically where the textInput size fits the content. The current code displays only 3 as the height of the gridLayout is set to 1000. I would like to use height: self.minimum_height so that I can dynamically add more textInputs and they will be displayed properly, however but cannot seem to get it working.
My kv file:
<MyNote#BoxLayout>:
orientation: 'vertical'
TextInput:
height: self.minimum_height
multiline: True
text_size: self.size
size_hint_y: None
text: '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15'
<MainNotesBoxLayout>
orientation: 'vertical'
ScrollView:
GridLayout:
cols: 1
size_hint_y: None
height: 1000
#height: self.minimum_height
MyNote:
MyNote:
MyNote:
My main file:
import kivy
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
class MainNotesBoxLayout(BoxLayout):
pass
class NotesApp(App):
def build(self):
return MainNotesBoxLayout()
if __name__ == '__main__':
NotesApp().run()

Replace GridLayout with BoxLayout
Set the minimum height of the boxlayout so that there is something to scroll.
ScrollView
layout.bind(minimum_height=layout.setter('height'))
Example
notes.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty
class MyNote(TextInput):
pass
class MainNotesBoxLayout(BoxLayout):
container = ObjectProperty(None)
def __init__(self, **kwargs):
super(MainNotesBoxLayout, self).__init__(**kwargs)
self.container.bind(minimum_height=self.container.setter('height'))
self.add_text_inputs()
def add_text_inputs(self):
for x in range(100):
my_note = MyNote()
self.container.add_widget(my_note)
class NotesApp(App):
def build(self):
return MainNotesBoxLayout()
if __name__ == '__main__':
NotesApp().run()
notes.kv
#:kivy 1.10.0
<MyNote>:
height: self.minimum_height
multiline: True
text_size: self.size
size_hint_y: None
text: '1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15'
<MainNotesBoxLayout>
container: container
orientation: 'vertical'
ScrollView:
size_hint: (1, 1)
bar_width: 10
bar_color: 1, 0, 0, 1 # red
bar_inactive_color: 0, 0, 1, 1 # blue
effect_cls: "ScrollEffect"
scroll_type: ['bars']
BoxLayout:
id: container
orientation: 'vertical'
size_hint: 1, None
Output

Related

Adding Kivy recycleview to screenmanager breaks example

I'm trying to combine this recycleview example with this screenmanager example so that the recycleview example can be one of the screens in my app. The app runs but all the control buttons display at the bottom of the UI (They're supposed to be at the top) and are either disabled or obscured, disallowing input. Consequently, the recycleview cannot be populated and/or viewed.
Here's my attempt:
import asyncio
from random import sample, randint
from string import ascii_lowercase
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.recycleview.views import RecycleDataViewBehavior
kv = '''
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
#:import BoxLayout kivy.uix.boxlayout.BoxLayout
#:import RecycleDataViewBehavior kivy.uix.recycleview.views.RecycleDataViewBehavior
ScreenManagement:
transition: FadeTransition()
ContactsScreen:
name: 'contacts'
MessengerScreen:
name: 'messenger'
<Row#RecycleKVIDsDataViewBehavior+BoxLayout>:
canvas.before:
Color:
rgba: 0.5, 0.5, 0.5, 1
Rectangle:
size: self.size
pos: self.pos
value: ''
Label:
id: name
Label:
text: root.value
<ContactsScreen>:
canvas:
Color:
rgba: 0.3, 0.3, 0.3, 1
Rectangle:
size: self.size
pos: self.pos
rv: rv
orientation: 'vertical'
GridLayout:
cols: 3
rows: 2
size_hint_y: None
height: dp(108)
padding: dp(8)
spacing: dp(16)
Button:
text: 'Populate list'
on_press: root.populate()
Button:
text: 'Sort list'
on_press: root.sort()
Button:
text: 'Clear list'
on_press: root.clear()
BoxLayout:
spacing: dp(8)
Button:
text: 'Insert new item'
on_press: root.insert(new_item_input.text)
TextInput:
id: new_item_input
size_hint_x: 0.6
hint_text: 'value'
padding: dp(10), dp(10), 0, 0
BoxLayout:
spacing: dp(8)
Button:
text: 'Update first item'
on_press: root.update(update_item_input.text)
TextInput:
id: update_item_input
size_hint_x: 0.6
hint_text: 'new value'
padding: dp(10), dp(10), 0, 0
Button:
text: 'Remove first item'
on_press: root.remove()
RecycleView:
id: rv
scroll_type: ['bars', 'content']
scroll_wheel_distance: dp(114)
bar_width: dp(10)
viewclass: 'Row'
RecycleBoxLayout:
default_size: None, dp(56)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
spacing: dp(2)
<MessengerScreen>:
Button:
on_release: app.root.current = 'contacts'
text: 'back to the home screen'
font_size: 50
'''
class ContactsScreen(Screen):
def populate(self):
self.rv.data = [
{'name.text': ''.join(sample(ascii_lowercase, 6)),
'value': str(randint(0, 2000))}
for x in range(50)]
def sort(self):
self.rv.data = sorted(self.rv.data, key=lambda x: x['name.text'])
def clear(self):
self.rv.data = []
def insert(self, value):
self.rv.data.insert(0, {
'name.text': value or 'default value', 'value': 'unknown'})
def update(self, value):
if self.rv.data:
self.rv.data[0]['name.text'] = value or 'default new value'
self.rv.refresh_from_data()
def remove(self):
if self.rv.data:
self.rv.data.pop(0)
class MessengerScreen(Screen):
pass
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_string(kv)
class MainApp(App):
def build(self):
return presentation
def main_runner(self):
async def run_wrapper():
# we don't actually need to set asyncio as the lib because it is
# the default, but it doesn't hurt to be explicit
await self.async_run(async_lib='asyncio')
print('App done')
#self.other_task.cancel()
return asyncio.gather(run_wrapper())
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(MainApp().main_runner())
loop.close()
The trouble seems to come from the <Row#RecycleKVIDsDataViewBehavior+BoxLayout> directive but I can't seem to fix it no matter where I place it.
You can position the Buttons using pos_hint, like this:
GridLayout:
id: grid
pos_hint: {'center_x': 0.5, 'top': 1}
Then, you need to size the RecycleView so that it is not over the Buttons, like this:
RecycleView:
id: rv
size_hint_y: None
height: root.height - grid.height

How to make MDCard expanding and collapsing with animation in Kivy

I am searching for a way to animate my MDCard when expanding or collapsing.
In my example, when I click my MDIconButton I want an animation that slowly expands or collapses the card.
I know there is an MDExpansionsPanel widget but for now, I'm not interested in using this. Is there an easy way to implement an animation that is similar to the ExpansionPanel?
main.kv
MDScreen:
MDBoxLayout:
orientation: "vertical"
MDCard:
id: card
orientation: "vertical"
md_bg_color: .7, .7, .7, 1
padding: dp(20)
size_hint: .5, None
height: self.minimum_height
pos_hint: {"center_x": .5}
MDIconButton:
icon: "chevron-down"
on_press: app.on_chevron()
Widget:
<Box>:
orientation: "vertical"
size_hint_y: None
height: self.minimum_height
main.py
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.core.window import Window
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.label import MDLabel
Window.size = {320, 600}
class Box(MDBoxLayout):
pass
class MainApp(MDApp):
def build(self):
self.is_expanded = False
return Builder.load_file("main.kv")
def on_chevron(self):
self.is_expanded = not self.is_expanded
card_layout = self.root.ids.card
if self.is_expanded:
item = Box()
for i in range(10):
item.add_widget(MDLabel(text=f"Lbl: {i}", size_hint=(1, None), height=20))
card_layout.add_widget(item)
else:
card_layout.remove_widget(card_layout.children[0])
if __name__ == "__main__":
MainApp().run()
You can use Animation to do that. Here is a modified version of your on_chevron() method that uses Animation:
def on_chevron(self):
self.is_expanded = not self.is_expanded
card_layout = self.root.ids.card
if self.is_expanded:
item = Box()
labels = []
for i in range(10):
# initialze Label with 0 height and font_size
l = Label(text=f"Lbl: {i}", color=(0,0,0,1), font_size=0, size_hint=(1, None), height=0)
item.add_widget(l)
labels.append(l)
card_layout.add_widget(item)
self.animate_labels(labels)
else:
card_layout.remove_widget(card_layout.children[0])
def animate_labels(self, labels):
anims = []
for i in range(len(labels)):
anims.append(Animation(height=20, font_size=15)) # animate height and font_size
for i in range(len(labels)):
anims[i].start(labels[i]) # start animations
I switched your MDLabel to Label just because MDLabel meddles with sizes. There may be a way to do this with the MDLabel.

Kivy make a grid layout inside a label or button

Is it possible to have a grid like layout inside a Label or a Button in kivy.
I have an app that takes in a CSV file with product information and I would like to populate MainScreen with rows from a CSV file.
Each row should look like this:
In the end the Label or Button should be pressable to open a pop up window for confirmation screen for quantity of the product and verify.
Is it even possible or am I approaching it from the wrong angle?
I do not have any code yet to populate the MainScreen with rows but this is how it looks so far.
To clarify. At this moment I don't need help with importing CSV files, but with the method to display it, that matches the above criteria(picture)
Code so far is as follows:
ATmain.py
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.core.window import Window
from kivy.lang import Builder
from kivy.properties import StringProperty
Window.clearcolor = (1,1,1,1)
Window.size = (270, 480)
class LoginScreen(Screen):
input = StringProperty("")
class MainScreen(Screen):
username = StringProperty('')
class ScreenManagement(ScreenManager):
pass
presentation = Builder.load_file("app.kv")
class ATApp(App):
presentation = Builder.load_file("app.kv")
def build(self):
return presentation
if __name__ == '__main__':
ATApp().run()
app.kv:
# File name: main.py
#:import FadeTransition kivy.uix.screenmanager.FadeTransition
#:kivy 1.10.1
ScreenManagement:
transition: FadeTransition()
LoginScreen:
id: login
MainScreen:
username: login.input
<LoginScreen>:
name: "login"
canvas:
Color:
rgba: [1,1,1]
Rectangle:
pos: self.pos
size: self.size
FloatLayout:
rows:2
cols:1
background_color: 1,1,1,1
Label:
size_hint: 0.3, 0.05
pos_hint: {"x": 0.5 - 0.3/2, "center_y": 0.4}
text:"Kasutaja"
color: 0,0,0,1
TextInput:
id: input
size_hint: (0.3, None)
height: 30
pos_hint: {"x": 0.5 - 0.3/2, "center_y": 0.3}
multiline: False
Button:
id: confirm_login
text: "Login"
size_hint: 0.15, 0.07
pos_hint: {"x": 0.5 - 0.15/2, "center_y": 0.2}
background_color: 0.9,0.9,0.9,1
on_press: self.background_color = (1,0,0,1)
on_release: root.input = input.text; app.root.current = "main"
<MainScreen>:
name: "main"
canvas:
Rectangle:
pos: self.pos
size: self.size
Label:
id:name
text: root.username
color: (0,0,0,1)
size_hint_y: None
height: 30
size_hint_x: 1
pos_hint: {"right": 1, "top": 1}
BoxLayout:
orientation: "vertical"
size_hint_y: None
size_hint_x: 1
pos_hint_x: None
pos_hint_y: 1
Button:
text: "Item1"
color: (0,0,0,1)
height: self.height
size_hint_y: None
size_hint_x: 1
pos_hint: {"right": 1, "top": 0}
I would be very greatful if anyone could as much as point me in the right direction!
The kivy hack way will be to simply use a GridLayout or any layout for that matter then give your layout button properties so it is clickable like so :
from kivy.behaviors import ButtonBehavior
#then make a clickable grid
class GridButton(GridLayout, ButtonBehaviour):
def __init__(self, **kwargs):
super().__init__(**kwargs)
#Then do whatever you want to do
Another way to do it I guess would be to use the on_touch_down callback and check if the touch is within the widget's bounds

Kivy: Popup can have only one widget as content

I am having an issue with using a popup in my .kv file. I understand that a popup can only have one widget as it's content, however if I am only passing a GridLayout as a child that includes a Label and Button, shouldn't this work?
Here is my Python code:
import kivy, LabelB
from kivy.app import App
from kivy.graphics import Color, Rectangle
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.tabbedpanel import TabbedPanel
from kivy.properties import ObjectProperty, StringProperty
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
Builder.load_file('main.kv')
class CustomPopup(Popup):
pass
class MenuScreen(Screen):
def open_popup(self):
the_popup = CustomPopup()
the_popup.open()
class SurveyScreen(Screen):
pass
sm = ScreenManager(transition=FadeTransition())
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(SurveyScreen(name='survey'))
class MainApp(App):
def build(self):
return sm
if __name__ == '__main__':
MainApp().run()
Here is my .kv file:
<CustomPopup>:
title: 'Terms of Service'
size_hint: .5, .5
auto_dismiss: False
GridLayout:
cols: 1
Label:
size_hint: .9, .9
halign: 'center'
valign: 'middle'
text: 'Insert terms of service text here'
text_size: self.width, None
Button:
text: 'Close'
on_release: root.dismiss()
<MenuScreen>:
FloatLayout:
canvas.before:
Rectangle:
source: 'menu.png'
size: self.size
pos: self.pos
Label:
pos_hint: {'x': .7, 'y': .85}
text_size: self.size
font_name: 'Arial'
font_size: 26
text: 'Sample'
bold: True
Button:
text: 'Take Survey'
size_hint: .2, .1
pos_hint: {'x': .15, 'y': .1}
on_release:
root.manager.transition.duration = 0.5
root.manager.current = 'survey'
Button:
text: 'Terms of Service'
size_hint: .2, .1
pos_hint: {'x': .6-self.size_hint_x, 'y': .1}
on_release: root.open_popup()
Button:
text: 'Quit'
size_hint: .2, .1
pos_hint: {'x': .85-self.size_hint_x, 'y': .1}
on_release: app.stop()
<SurveyScreen>:
GridLayout:
cols: 1
padding: 20
spacing: 10
Label:
text: 'WELCOME!'
font_size: 20
Label:
text: 'Some boring text'
The error is as follows: 'Popup can have only one widget as content'
Am I missing something obvious here? Thanks in advance.
Yes, it should work as you say, your code is correct.
The problem is that the loading of the .kv file is duplicated. As your App subclass is called MainApp, main.kv is loaded automatically if it is in same directory (Doc: How to load kv). On the other hand, you explicitly upload the file using Builder.load_file ('main.kv').
You must remove the call to Builder or rename MainApp/main.kv.
If you delete the call to Builder.load_file you must create the ScreenManager instance once the .kv is loaded. You can do something like:
class MainApp (App):
def build (self):
sm = ScreenManager (transition = FadeTransition ())
sm.add_widget (MenuScreen (name = 'menu'))
sm.add_widget (SurveyScreen (name = 'survey'))
return sm

Kivy Scrollable Label and text file, label wont update

Hy, the problem is that with the current code, which is at this point preety much nothing but a text editor, when ever I try to make a scrollable label in the kv language and call it on the main screen at the push of a button, I get no error, theres just nothing there. I should mention that the text is taken from a stored file, and the only version that works is with a regular label. This is the code, I know its a bit long but its preety easy to understand so stay with me. Any sort of input is greatly apreciated and I thank you for taking the time.
#kivy.require("1.8.0")
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.textinput import TextInput
from kivy.properties import StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.graphics import Line
from kivy.uix.gridlayout import GridLayout
kv = '''
#: import FadeTransition kivy.uix.screenmanager.FadeTransition
ScreenManager:
transition: FadeTransition()
MainScreen:
AddScreen:
AppendScreen:
<ScatterTextWidget>:
orientation: 'vertical'
TextInput:
id: main_input
font_size: 14
size_hint_y: None
height: root.height - botones_layout.height
font_color: [0.1,0.3,0.9,1]
focus: True
foreground_color: [0.2,0.5,0.9,1]
cursor_color: [0,0,1,1]
BoxLayout:
id: botones_layout
orientation: 'horizontal'
height: 30
Button:
id: home_button
text: "Back Home"
Button:
id: save_button
text: "Save to file"
on_press: root.saveToFile("Archive.txt", main_input.text)
<AppendTextWidget>:
orientation: 'vertical'
TextInput:
text: root.text
id: main_input
font_size: 14
size_hint_y: None
height: root.height - botones_layout.height
font_color: [0.1,0.3,0.9,1]
focus: True
foreground_color: [0.2,0.5,0.9,1]
cursor_color: [0,0,1,1]
BoxLayout:
id: botones_layout
orientation: 'horizontal'
height: 30
Button:
id: home_button
text: "Back Home"
on_release: app.root.current = "main"
Button:
id: save_button
text: "Save"
on_press: root.append(main_input.text)
#This does not work <--- <--- <---
<ScrollableLabel>:
Label:
text: root.text
font_size: 15
text_size: self.width, None
color: [0,255,0,1]
padding_x: 20
size_hint_y: None
pos_hint: {"left":1, "top":1}
height: self.texture_size[1]
<MainScreen>:
name: "main"
FloatLayout:
# This does work
Label:
text: root.text
font_size: 15
text_size: self.width, None
color: [0,255,0,1]
padding_x: 20
size_hint_y: None
pos_hint: {"left":1, "top":1}
height: self.texture_size[1]
ActionBar:
pos_hint: {'top':1}
ActionView:
use_separator: True
ActionPrevious:
title: "Text"
with_previous: False
ActionOverflow:
ActionButton:
text: "New"
on_release: app.root.current = "add"
ActionButton:
text: "Update"
on_press: root.clicked()
ActionButton:
text: "Add"
on_release: app.root.current = "append"
<AddScreen>:
name: "add"
FloatLayout:
ScatterTextWidget
<AppendScreen>:
name: "append"
FloatLayout:
AppendTextWidget
'''
class ScatterTextWidget(BoxLayout):
def saveToFile(self,name,text):
f = open(name, "w")
f.write("\n\n\n" + " " + ">>>" + text + "test"*500)
f.close()
class AppendTextWidget(BoxLayout):
text = StringProperty("")
def append(self,text):
with open("Archive.txt", "a") as f:
f.write("\n" + " " + ">>>" + text)
f.close()
class ScrollableLabel(ScrollView):
text = StringProperty('')
pass
class MainScreen(Screen):
text = StringProperty("")
def clicked(self):
with open("Archive.txt", "r") as f:
contents = f.read()
self.text = contents
pass
class AddScreen(Screen):
pass
class AppendScreen(Screen):
pass
class MyApp(App):
def build(self):
return Builder.load_string(kv)
if __name__ == '__main__':
MyApp().run()
Why it works:
Your text in MainScreen is updated from file, then passed to Label and the text is loaded. ScrollableLabel.text stays unchanged.
Why it doesn't work as you expect:
There's no communication between your classes, therefore only text changed is an actual self.text = MainScreen.text
How to make it work:
Either use something on a global range, i.e. variable in your App class, then a = App.get_running_app() and access variable through a.<variable> or use __init__ to initialize your ScrollableLabel inside the MainScreen and pass it the text
So it's basically a duplicate of this and that one is a duplicate of an older unsimplified question.

Resources