I created a mobile app. Once a user clicks on 1 element on the list I need the text to go into another text-input
My kv file
#:import main main
#:import ListAdapter kivy.adapters.listadapter.ListAdapter
#:import ListItemButton kivy.uix.listview.ListItemButton
<LocationButton>:
deselected_color:0.4, 1, 1,1
selected_color: 0, 0, 1, 1
size: (100, '48dp')
on_press:root.test()
<ecran1>:
nom_du_produit:le_produit
FloatLayout:
ListView:
id:liste_des_produits
size_hint:.5,.8
pos_hint:{'x':.25,'y':.0}
adapter:
ListAdapter(data=root.L,cls=main.LocationButton)
TextInput:
id:le_produit
text:''
font_size:20
size_hint:.2,.1
pos_hint:{'x':.78,'y':.75}
background_color:1,1,1,1
multiline:False
My python code
import kivy
from kivy.app import App
from kivy.uix.screenmanager import Screen,ScreenManager,WipeTransition
from kivy.properties import ObjectProperty,StringProperty,ListProperty
from kivy.uix.listview import ListItemButton
class ecran1(Screen):
L=ListProperty(['tomate','abricot'])
nom_du_produit = ObjectProperty()
class LocationButton(ListItemButton):
L = ListProperty(['tomate', 'abricot'])
nom_du_produit = ObjectProperty()
def test(self):
selection_1 = self.liste.adapter.selection[0].text
self.nom_du_produit.text = selection_1
class PongApp(App):
def build(self):
return ecran1()
if __name__ == '__main__':
PongApp().run()
I tried few options but always the answer is Attribute error
Picture to better understand:This Picture
There are at least two different ways to accomplish what you want. Here is a modification of your test method that shows both:
def test(self):
#App.get_running_app().root.nom_du_produit.text = self.text # uses the ObjectProperty in the ecran1 class
App.get_running_app().root.ids.le_produit.text = self.text # uses the le_produit id in the TextInput class
Related
I wanted to know how can i make communication between multiple classes of the layout. I'm trying to make the button on the MainLayout called add, add another button to the stacklayout which is one of its children.
in doing so, I have to both share a variable and also a functionality between them to implement the add_widget function on the stack layout. no matter what I do, I can't find a solution
code main.py:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.metrics import dp
from kivy.uix.stacklayout import StackLayout
class Buttons_layout(StackLayout):
def __init__(self,**kwargs):
super().__init__(**kwargs)
self.number = 0
for _ in range(5):
self.number += 1
self.add_widget(Button(text=str(self.number),color=(200,100,100),size_hint=(0.2,None),height=dp(100)))
class MainWidget(BoxLayout):
def __init__(self,**kwargs):
super().__init__(**kwargs)
def add_button(self):
#dont know what to do here..................
pass
class CanvosExampleApp(App):
pass
if __name__ == '__main__':
CanvosExampleApp().run()
and the kv file:
MainWidget:
<Buttons_layout>:
<Scroll_layout#ScrollView>:
Buttons_layout:
size_hint: 1,None
height:self.minimum_height
<MainWidget>:
Button:
text:'add'
on_press: root.add_button()
size_hint:None,1
width:dp(50)
Scroll_layout:
To allow easy navigation in your GUI, you can use ids. Here is a modified version of your kv with two new ids:
MainWidget:
<Buttons_layout>:
<Scroll_layout#ScrollView>:
Buttons_layout:
id: butts # new id
size_hint: 1,None
height:self.minimum_height
<MainWidget>:
Button:
text:'add'
on_press: root.add_button()
size_hint:None,1
width:dp(50)
Scroll_layout:
id: scroll # new id
Then, your add_button() method can be:
def add_button(self):
scroll = self.ids.scroll # get reference to the Scroll_layout
butts = scroll.ids.butts # get reference to the Buttons_layout
butts.add_widget(Button(text='Added',color=(200,100,100),size_hint=(0.2,None),height=dp(100)))
I am building a German dictionary app where there is an option to get gender of German nouns in Kivy python and I wanted to have an unfocus event in the Text Input so only when the user unfocuses from the
'MDTextFieldRound' , the search method can be called which will give the list of all german nouns according to entered prefix in the MDTextField...
Here is the main python file:
from kivymd.app import MDApp
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty
from kivymd.uix.textfield import MDTextFieldRound
from mst import genderGetter
from kivymd.uix.list import TwoLineListItem
class MenuScreen(Screen):
pass
class GenderGameScreen(Screen):
pass
class GenderScreen(Screen):
words = list(genderGetter().keys())
def get_len(self):
return len(self.get_text())
def search(self):
self.get_text()
self.create_list()
def get_text(self):
gen = self.ids.gender.text.lower().capitalize()
return gen
def create_list(self):
for word in self.words:
if self.get_text() in word[0:self.get_len()]:
items = TwoLineListItem(text=word, secondary_text=genderGetter().get(word))
self.ids.contain.add_widget(items)
class GenderText(MDTextFieldRound):
pass
class TranslatorScreen(Screen):
pass
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
class GermanApp(MDApp):
def build(self):
self.theme_cls.primary_palette = "Blue"
screen = Builder.load_file('kv files/main.kv')
return screen
if __name__ == "__main__":
app = GermanApp()
app.run()
Here is the kivy file of gender.kv
<GenderScreen>:
id:genders
name:'gender'
ScrollView:
size_hint:(.5,.8)
MDList:
id: contain
MDTextFieldRound:
id: gender
hint_text: "Enter the German noun"
helper_text: "Correct one"
helper_text_mode: "on_focus"
pos_hint : {"center_x" : 0.45 , "center_y" : 0.9}
icon_right_color:app.theme_cls.primary_color
size_hint_x : 0.8
on_text:root.search()
I am still a noob in kivy so there can be many potential mistakes in code...
Please consider that..
I am trying to make a program that reads the dictionary after the user inputs their name and assigns a random selection based on weighted values in the dictionary. As of now the logic for selecting a random value from the dictionary is working but I have it printing to the console. I would like it to appear in a popup window (which i have but cannot get the output variable to show up there)
four.kv
WindowManager:
MainWindow:
<MainWindow>:
name:'main'
player_python:player_kv
GridLayout:
cols:1
GridLayout:
cols:2
Label:
text:'Player:'
TextInput:
id: player_kv
multiline: False
Button:
text: 'Random'
on_press: root.btn()
<P>:
output:output
FloatLayout:
Label:
id: output
main4.py
import kivy
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.widget import Widget
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.floatlayout import FloatLayout
from kivy.properties import StringProperty
import random
#from Dict import *
#### example dictionary
character = {
'John':
{'Water': 2, #50%
'Fire': 1, #25%
'Earth': 1,}, #25%
'Bill':
{'Water': 1, #25%
'Fire': 2, #50%
'Earth': 1,}} #25%
####
class MainWindow(Screen):
player_python = ObjectProperty(None)
output = StringProperty('')
def btn(self):
show_popup()
player = self.player_python.text
weighted_list = []
for c in character[player]:
for w in range(character[player][c]):
weighted_list.append(c)
self.output= random.choice(weighted_list)
print(self.output) ###### instead of this printing to console I want it to display in popup window
self.player_python.text = ''
class P(FloatLayout):
pass
def show_popup():
show = P()
popupWindow = Popup(title='random character', content=show, size_hint=(None,None),size=(400,400) )
popupWindow.open()
class WindowManager(ScreenManager):
pass
kv = Builder.load_file('four.kv')
class FourApp(App):
def build(self):
return kv
if __name__ == '__main__':
FourApp().run()
https://gist.github.com/PatrickToole/00cc72cdd7ff5146976e5d92baad8e02
Thanks in advance
-P
I haven't tested this code, but try passing self.output to your show_popup() method. This would mean changing your btn() method to something like:
def btn(self):
player = self.player_python.text
weighted_list = []
for c in character[player]:
for w in range(character[player][c]):
weighted_list.append(c)
self.output= random.choice(weighted_list)
print(self.output) ###### instead of this printing to console I want it to display in popup window
self.player_python.text = ''
show_popup(self.output)
And in the show_popup() method:
def show_popup(output):
show = P()
show.output.text = output
popupWindow = Popup(title='random character', content=show, size_hint=(None,None),size=(400,400) )
popupWindow.open()
As I mentioned, I haven't tested this code, but something like this should work.
I'm trying to implement FlatButton in my kv but I keep getting the same error that is AttributeError: 'NoneType' object has no attribute 'bind. It works fine with Button alone.
from flat_kivy.flatapp import FlatApp
from kivy.uix.touchripple import TouchRippleBehavior
from kivy.uix.button import Button
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.properties import (StringProperty, NumericProperty, ObjectProperty,
ListProperty, DictProperty, BooleanProperty)
class Login(Screen):
pass
class MainScreen(Screen):
pass
class ScreenManager(ScreenManager):
pass
theRoot = Builder.load_string('''
ScreenManager:
Login:
<Login>:
FlatButton:
text: 'Click Here'
size_hint: (.4,.25)
''')
class TouchRippleApp(FlatApp):
def build(self):
return theRoot
if __name__ == '__main__':
TouchRippleApp().run()
This is the FlatButton code in Flat_Kivy. I'm stuck at this problem.
class FlatButtonBase(GrabBehavior, LogBehavior, TouchRippleBehavior,
ThemeBehavior):
color = ListProperty([1., 1., 1.])
color_down = ListProperty([.7, .7, .7])
border_size = ListProperty([0, 0, 0, 0])
text = StringProperty('')
alpha = NumericProperty(1.0)
style = StringProperty(None, allownone=True)
color_tuple = ListProperty(['Grey', '500'])
font_color_tuple = ListProperty(['Grey', '1000'])
ripple_color_tuple = ListProperty(['Grey', '1000'])
font_ramp_tuple = ListProperty(None)
font_size = NumericProperty(12)
eat_touch = BooleanProperty(False)
def on_color(self, instance, value):
self.color_down = [x*.7 for x in value]
class FlatButton(FlatButtonBase, ButtonBehavior, AnchorLayout):
pass
class RaisedFlatButton(RaisedStyle, FlatButton):
pass
Perhaps an easier way to do this altogether is create your FlatButton class in the .kv language (inside your string you're loading with Builder.load_string)
Try adding this to your kv string:
<FlatButton#Button>: # create a class "FlatButton" that inherits the kivy Button
background_normal: "" # Get rid of the kivy Button's default background image
background_down: "" # Get rid of the kivy Button's default background image when clicked
# Set the background color to transparent if no action is happening to the button
# If the button is clicked, it will change it to fully white
background_color: (1,1,1,0) if self.state == 'normal' else (1,1,1,1)
and then you can remove all the code relating to your FlatButton class on the python side, with the exception of creating a base class for the kv to work with. E.g. all you need in the python code is
class FlatButton():
pass
I am trying to update a label field dynamically from the contents of a TextInput in a ModalView. The idea is that in the TextInput one enters plain text including markup formatting and you will see the results directly in the Label field with markup = True.
Unfortunately I do not know how to access the Label item in the ModalView. Who can help? See the example code below.
Thanks in advance.
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.modalview import ModalView
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.properties import ObjectProperty, StringProperty
kv = """
<Test>:
canvas:
Color:
rgba: 0.4, 0.5, 0.6, 1
Rectangle:
size: self.size
pos: self.pos
Button:
size_hint: None, None
size: 3 * dp(48), dp(48)
text: 'Edit'
on_press: root.showedit()
"""
Builder.load_string(kv)
class Test(BoxLayout):
minput_text = StringProperty('Welcome')
txtresult = ObjectProperty()
def showedit(self):
mview = ModalView(id='mviewid', size_hint=(0.4, 0.6), auto_dismiss=False, background='./images/noimage.png')
mblt = BoxLayout(orientation='vertical', padding=(24))
minp = TextInput(id='inptxt', text='', hint_text='Start typing text with markup here', size_hint=(1,0.5),multiline=True)
minp.bind(text=self.on_inptext)
mtxt = Label(id='txtresult',text='displays formatted text', color=(0.3,0.3,0.3), size_hint=(1,0.5),markup=True)
mcnf = Button(text='OK', size=(144,48), size_hint=(None,None))
mcnf.bind(on_press=mview.dismiss)
mblt.add_widget(minp)
mblt.add_widget(mtxt)
mblt.add_widget(mcnf)
mview.add_widget(mblt)
mview.bind(on_dismiss=self.print_text)
mview.open()
def on_inptext(self, instance, value):
self.minput_text = value
def print_text(self, *args):
print self.minput_text
class TestApp(App):
def build(self):
return Test()
if __name__ == '__main__':
TestApp().run()
You have to make a binding between the TextIntput text and the Label, for this we can use a lambda function and setattr.
class Test(BoxLayout):
minput_text = StringProperty('Welcome')
txtresult = ObjectProperty()
def showedit(self):
mview = ModalView(id='mviewid', size_hint=(0.4, 0.6), auto_dismiss=False, background='./images/noimage.png')
mblt = BoxLayout(orientation='vertical', padding=(24))
minp = TextInput(id='inptxt', text='', hint_text='Start typing text with markup here', size_hint=(1,0.5),multiline=True)
minp.bind(text=self.on_inptext)
mtxt = Label(id='txtresult',text='displays formatted text', color=(0.3,0.3,0.3), size_hint=(1,0.5),markup=True)
mcnf = Button(text='OK', size=(144,48), size_hint=(None,None))
mcnf.bind(on_press=mview.dismiss)
mblt.add_widget(minp)
mblt.add_widget(mtxt)
mblt.add_widget(mcnf)
mview.add_widget(mblt)
mview.bind(on_dismiss=self.print_text)
# binding between TextInput text and Label text
minp.bind(text=lambda instance, value: setattr(mtxt, 'text',value))
mview.open()
def on_inptext(self, instance, value):
self.minput_text = value
def print_text(self, *args):
print(self.minput_text)