KIVY python - change TextInput color - kivy

I want to change the color of text contained in the TextInput when it is modified by the user.
Example:
There is a text input, with a 'pre-written' text inside
If you modify a character of this text, its color immediately changes to red
debug2.py
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
class MyDebug(BoxLayout):
def __init__(self, **kwargs):
super(MyDebug, self).__init__(**kwargs)
Builder.load_file("debug2.kv")
class MyAppli(App):
def build(self):
return MyDebug()
if __name__ == '__main__':
MyAppli().run()
debug2.kv
#:kivy 1.9.1
<MyDebug>:
TextInput:
text: "Edit me !" # change color to (1, 0, 0, 1) when modified
foreground_color: (0.3, 0.4, 0.5, 1)

Here you go
py:
class ColorTextInput(TextInput):
def changetored(self):
if self.text != "Edit me !":
self.foreground_color = (1,0,0,1)
kv:
ColorTextInput:
text: "Edit me !" # change color to (1, 0, 0, 1) when modified
on_text: self.changetored()

You add a method into your root widget, MyDebug and an event, on_text into your kv file as follow:
Snippet
debug2.py
class MyDebug(BoxLayout):
def __init__(self, **kwargs):
super(MyDebug, self).__init__(**kwargs)
def on_text_change(self, instance, value):
instance.foreground_color = (1, 0, 0, 1)
debug2.kv
<MyDebug>:
TextInput:
text: "Edit me !" # change color to (1, 0, 0, 1) when modified
foreground_color: (0.3, 0.4, 0.5, 1)
on_text: root.on_text_change(self, self.text)
Output

Easiest way to change the color of the text is to use on_text
TextInput:
text: 'Color will change from black to red if text is modified'
on_text: self.foreground_color = (1,0,0,1)##red
foreground_color = (0,0,0,1)

You can use the example below:
TextInput:
id: txt_add_data_trial
multiline: True
cursor_color: app.theme_cls.primary_color
font_family: 'Roboto'
font_size: '20sp'
size_hint: 1, None
height: '60dp'
foreground_color: app.theme_cls.primary_color if self.focus==True else self.disabled_foreground_color
background_normal: './assets/imgs/transparent.png'
background_active: './assets/imgs/transparent.png'
canvas.after:
Color:
group: "color"
rgba: app.theme_cls.primary_color if self.focus==True else C('#d3d3d3')
Line:
group: "rectangle"
width: dp(1.25)
rectangle: (self.x, self.y, self.width, self.height)

Related

Unknown class <DrawerClickableItem>"

i want to add items to NavigationDrawer but i get this "Unknown class " errors instead.
i tried defining a Class "DrawerClickableItem" but it wouldn't work instead i get errors. i have tried several options that seem to work but "DrawerClickableItem" always gives an error. the codes are below.
python code
from kivymd.app import MDApp
from kivy.core.window import Window
from kivy.lang.builder import Builder
from kivymd.uix.screenmanager import ScreenManager
from kivy.uix.boxlayout import BoxLayout
Window.size = [320, 600]
class ShopApp(MDApp):
def build(self):
global screen_manager
screen_manager = ScreenManager()
screen_manager.add_widget(Builder.load_file('home.kv'))
screen_manager.add_widget(Builder.load_file('Sign_up.kv'))
screen_manager.add_widget(Builder.load_file('login.kv'))
return screen_manager
ShopApp().run()
kv file
MDScreen:
name: 'home'
md_bg_color: 1, 1, 1, 1
background_normal: ''
MDNavigationLayout:
ScreenManager:
Screen:
BoxLayout:
orientation: 'vertical'
MDTopAppBar:
md_bg_color: [0, 0, 0, 1]
elevation: 2.5
title: "Home"
left_action_items: [['menu', lambda x: nav_drawer.set_state("open")]]
Widget:
MDNavigationDrawer:
id: nav_drawer
size_hint: .3, .9
radius: (0, 30, 30, 0)
md_bg_color: 0, 0, 0, 1
pos_hint: {'y': .1}
scrim_color: 0, 0, 0, 0
MDNavigationDrawerMenu:
MDNavigationDrawerHeader:
title: "Header title"
title_color: "#4a4939"
text: "Header text"
spacing: "4dp"
padding: "12dp", 0, 0, "56dp"
MDNavigationDrawerLabel:
text: "Mail"
DrawerClickableItem:
icon: "gmail"
right_text: "+99"
text_right_color: "#4a4939"
text: "Inbox"
DrawerClickableItem:
icon: "send"
text: "Outbox"
MDNavigationDrawerDivider:
MDNavigationDrawerLabel:
text: "Labels"
DrawerLabelItem:
icon: "information-outline"
the new class needs to be defined and inherit one that exists.
this can be done in a .kv file that you load with Builder.loadfile("filename.kv") or put this code in a .kv file that you already have. properties can be defined such as the size hint that I placed as an example.
<DrawerClickableItem#MDNavigationDrawer>:
size_hint_x: 5

KV file popup does not respond with proper action

My popup.KV file content:
<ConfirmPopup>:
cols:1
Label:
text: root.text
canvas.before:
Color:
rgba: 1, 0, 1, 0.4
Rectangle:
size: self.size
pos: self.pos
GridLayout:
cols: 2
size_hint_y: None
height: '44sp'
Button:
text: 'Yes'
canvas.before:
Color:
rgba: 0, 1, 0, 1
Rectangle:
size: self.size
pos: self.pos
on_release: root.dispatch('on_answer','yes')
Button:
text: 'No'
canvas.before:
Color:
rgba: 1, 0, 0, 1
Rectangle:
size: self.size
pos: self.pos
on_release: root.dispatch('on_answer', 'no')
and the popup.PY file:
from kivy.lang import Builder
from kivy.uix.gridlayout import GridLayout
from kivy.uix.popup import Popup
from kivy.properties import StringProperty
class ConfirmPopup(GridLayout):
text = StringProperty('AAAA')
def __init__(self, **kwargs):
self.register_event_type('on_answer')
super(ConfirmPopup, self).__init__(**kwargs)
def on_answer(self, *args):
pass
class PopupTest():
def __init__(self):
self.popup = None
def build(self):
Builder.load_file('popup.kv')
content = ConfirmPopup(text='Do You Love Kivy?')
content.bind(on_answer=self._on_answer)
self.popup = Popup(title="Answer Question",
content=content,
size_hint=(None, None),
size=(480, 400),
auto_dismiss=False)
self.popup.open()
def _on_answer(self, instance, answer):
print("USER ANSWER: ", repr(answer))
self.popup.dismiss()
def show():
pop = PopupTest()
pop.build()
THis is the app.py file that uses the popup
import kivy
from kivy.app import App
from popup import *
class PopTest(App):
show()
if __name__ == '__main__':
PopTest().run()
My problem is that the popup displays correctly, the buttons blink when clicked BUT the appropriate message is not printed and the popup is not dismissed when a button is clicked. To me it looks like the button event is not bound to the actions. How do I fix it.
Thanks for a fix and any explanations.
Your PopupTest class must be an EventDispatcher in order for your code to work as you want. Just modify PopupTest slightly:
class PopupTest(Widget):
def __init__(self):
super(PopupTest, self).__init__()
self.popup = None

Positioning a text field inside a toolbar in Kivy

I'm trying to put a textfield inside a toolbar with KivyMD, but the textfield is always directly against the right side of the window. I tried to adjust it with pos_hint, but none of the values I put for the x-coordinates moved it.
Screen:
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: 'assets/bg.png'
BoxLayout:
orientation: 'vertical'
MDToolbar:
id: toolbar
title: 'Placeholder'
elevation: 10
pos_hint: {"top": 1}
left_action_items: [['menu', lambda x: app.menu.open()]]
MDTextFieldRound:
id: textinput
icon_left: 'magnify'
pos_hint: {'x': 0.1 ,'center_y': 0.5, 'right': 0.3}
size_hint: {.6, .4}
text_color: 'white'
hint_text: 'Search'**strong text**
MDLabel:
text: 'Placeholder'
color: 'white'
halign: 'center'
Screenshot of toolbar
Any help is appreciated, thanks.
You can insert your widgets wherever you want, for this you can specify a position in the widget tree - add_widget(widget, index). I wrote a special get_widgets function for your solution, which goes through all the widgets in the class. In the example below, you can place the text field on the left, right, and center. Also examine the MDToolbar source code
from kivy.lang.builder import Builder
from kivy.metrics import dp
from kivy.clock import Clock
from kivy.weakproxy import WeakProxy
from kivymd.app import MDApp
from kivymd.uix.boxlayout import MDBoxLayout
from kivymd.uix.textfield import MDTextField
KV = """
MDScreen:
MDBoxLayout:
orientation: 'vertical'
MDToolbar:
id: toolbar
title: 'Placeholder'
pos_hint: {"top": 1}
MDLabel:
text: 'Placeholder'
color: 'white'
halign: 'center'
"""
class TestApp(MDApp):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.search_content = None
def build(self):
return Builder.load_string(KV)
def on_start(self):
Clock.schedule_once(lambda dt: self.add_search('left'))
#staticmethod
def get_widgets(root: WeakProxy, class_: str):
"""
:param root: root widget
:param class_: which subclass are we looking for
:return:
"""
widgets = []
for widget in root.walk():
if widget.__class__.__name__ == class_:
widgets.append(widget)
print(widget)
return widgets
def add_search(self, side: str):
"""
:param side: left/right/center
:return:
"""
box = self.get_widgets(self.root.ids.toolbar, 'MDBoxLayout')[0] # get root `MDBoxLayout`
if side == 'left':
index = 2
elif side == 'right':
index = 1
else:
index = 0
self.root.ids.toolbar.ids.label_title.size_hint = None, None
self.root.ids.toolbar.ids.label_title.opacity = 0
# NOTE: If you remove this `MDLabel`, you cant change `self.theme_cls.material_style`
# box.remove_widget(self.root.ids.toolbar.ids.label_title)
boxlayout = MDBoxLayout(padding=[dp(18), dp(0), dp(18), dp(18)])
self.search_content = MDTextField(icon_left='magnify',
mode='round',
color_mode="custom",
line_color_normal=(1, 0, 1, 1),
line_color_focus=(0, 0, 1, 1),
text_color_focus=self.theme_cls.text_color,
text_color_normal=self.theme_cls.text_color[0:3] + [0.7],
hint_text='Empty field',
)
boxlayout.add_widget(self.search_content)
box.add_widget(boxlayout, index)
TestApp().run()

Kivy: Don't know how to update "on_size: root.center = win.Window.center" in ScreenManager

I added the Kivy scatter example to a kivy screen. But it didn´t work properly. I have to reconfigure the center on the window. It's done in the kv-file. But I don´t know how to do it on a screen. See the code below.
python
class Picture(Scatter):
source = StringProperty(None)
class ScreenThree(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
root = BoxLayout() # instantiate BoxLayout
self.add_widget(root) # add BoxLayout to screen
curdir = dirname(__file__)
for filename in glob(join(curdir, 'images', '*')):
print(filename)
try:
picture = Picture(source=filename, rotation=randint(-30, 25))
root.add_widget(picture)
except Exception as e:
Logger.exception('Pictures: Unable to load <%s>' % filename)
def on_pause(self):
return True
class TestApp(App):
def build(self):
sm = ScreenManager()
sc1 = ScreenOne(name='screen1')
sc2 = ScreenTwo(name='screen2')
sc3 = ScreenThree(name='screen3')
sm.add_widget(sc1)
sm.add_widget(sc2)
sm.add_widget(sc3)
print (sm.screen_names)
return sm
if __name__ == '__main__':
TestApp().run()
kivy
#:kivy 1.0
#:import kivy kivy
#:import win kivy.core.window
FloatLayout:
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
source: 'data/images/background.jpg'
size: root.size
BoxLayout:
padding: 10
spacing: 10
size_hint: 1, None
pos_hint: {'top': 1}
height: 44
Image:
size_hint: None, None
size: 24, 24
source: 'data/logo/kivy-icon-24.png'
Label:
height: 24
text_size: self.width, None
color: (1, 1, 1, .8)
text: 'Kivy %s - Pictures' % kivy.__version__
<Picture>:
on_size: root.center = win.Window.center <-- this is the question i guess
size: image.size
size_hint: None, None
Image:
id: image
source: root.source
# create initial image to be 400 pixels width
size: 400, 400 / self.image_ratio
# add shadow background
canvas.before:
Color:
rgba: 1,1,1,1
BorderImage:
source: 'shadow32.png'
border: (36,36,36,36)
size:(self.width+72, self.height+72)
pos: (-36,-36)
See the example here, Kivy Gallery of Examples » Basic Picture Viewer
In the kv file, on_size: root.center = win.Window.center will work fine, when you make the instantiated object, FloatLayout: as child of class rule, <ScreenThree>: plus some enhancements in Python script.
kv file
Replace #:kivy 1.0 with the Kivy version installed e.g. #:kivy 1.11.1
Add class rule, <ScreenThree>: and make FloatLayout: object as child of <ScreenThree>:
Snippets - kv file
<ScreenThree>:
FloatLayout:
canvas:
Color:
rgb: 1, 1, 1
Rectangle:
source: 'data/images/background.jpg'
size: root.size
BoxLayout:
padding: 10
spacing: 10
size_hint: 1, None
pos_hint: {'top': 1}
height: 44
Image:
size_hint: None, None
size: 24, 24
source: 'data/logo/kivy-icon-24.png'
Label:
height: 24
text_size: self.width, None
color: (1, 1, 1, .8)
text: 'Kivy %s - Pictures' % kivy.__version__
py file
Remove root = BoxLayout() and self.add_widget(root)
Replace root.add_widget(picture) with self.add_widget(picture)
Snippets - py file
class ScreenThree(Screen):
def __init__(self, **kwargs):
super().__init__(**kwargs)
curdir = dirname(__file__)
for filename in glob(join(curdir, 'images', '*')):
print(filename)
try:
picture = Picture(source=filename, rotation=randint(-30, 25))
self.add_widget(picture)
except Exception as e:
Logger.exception('Pictures: Unable to load <%s>' % filename)
Output

Kivy: how to update a label when a button is clicked

I use a button to retrieve the paths of some folders selected with the filechooser. When the button is clicked I would like to update the text of the label so that it dispays the selected paths.
In my Kv:
Button:
text:'OK'
on_press: root.selected(filechooser.path, filechooser.selection)
Label:
id: Lb_ListViewFolder
text: root.Lb_ListViewFolder_text
color: 0, 0, 0, 1
size_hint_x: .75
In .py:
class MyWidget(BoxLayout):
Lb_ListViewFolder_text = ObjectProperty("Text")
def selected(self, a, b):
global Lb_ListViewFolder_text
Lb_ListViewFolder_text = b
print(a,b)
This doesn't give me any error but the label text isn't changed.
I also tried self.ListViewFolder.text = b like recommended here but I get this error: MyWidget' object has no attribute 'Lb_ListViewFolder'.
I have seen this answer, but I have trouble applying in my code
I use python 3.6 and Kivy 1.9.2.dev0
In case, this is my entire code:
from kivy.properties import ObjectProperty
from kivy.core.window import Window
from kivy.event import EventDispatcher
from kivy.lang import Builder
root = Builder.load_string('''
<MyWidget>
id: BL_Main
orientation: "horizontal"
padding: 10
spacing: 10
BoxLayout:
id: BL_folder
orientation: "vertical"
Button:
id:ok
text:'OK'
background_color: 0,0,1,1
height: 5
size_hint: 0.1, 0.1
on_press: root.selected(filechooser.path, filechooser.selection)
BoxLayout:
orientation:"horizontal"
size_hint: None, 0.9
width:150
canvas.before:
Color:
rgb: .4,.5,.5
Rectangle:
pos: self.pos
size: self.size
## multiple select folder not possible with FileChooserListView
FileChooserIconView:
id: filechooser
pos:self.pos
multiselect: True
dirselect: True
Label:
id: Lb_ListViewFolder
text: root.Lb_ListViewFolder_text
color: 0, 0, 0, 1
size_hint_x: .75
''')
class MyWidget(BoxLayout):
Lb_ListViewFolder_text = ObjectProperty("Text")
def selected(self, a, b):
global Lb_ListViewFolder_text
Lb_ListViewFolder_text = b
print(a,b)
class MyApp(App):
def build(self):
Window.clearcolor = (1, 1, 1, 1)
return MyWidget()
MyApp().run()
You can use StringProperty here:
from kivy.app import App
from kivy.uix.filechooser import FileChooserListView
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder
from kivy.properties import StringProperty
Builder.load_string('''
<MyLayout>:
orientation: "vertical"
Label:
text: root.label_text
Button:
id:ok
text:'OK'
on_press: root.selected(filechooser.path, filechooser.selection)
FileChooserIconView:
id: filechooser
pos:self.pos
multiselect: True
dirselect: True
''')
class MyLayout(BoxLayout):
label_text = StringProperty("File name")
def selected(self, a, b):
self.label_text = b[0]
class MyApp(App):
def build(self):
return MyLayout()
MyApp().run()
Or you can change it directly in kvlang:
<MyLayout>:
orientation: "vertical"
Label:
id: dirlabel
text: root.label_text
Button:
id:ok
text:'OK'
on_press: dirlabel.text = filechooser.selection[0]
FileChooserIconView:
id: filechooser
pos:self.pos
multiselect: True
dirselect: True

Resources