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..
Related
output KivyMD Programmers, im new in KivyMD....
on_start() list items are sucessfully showing and on_press sending a selected value too passValue() function....
but here now i wants open new Screen under passValue() function...and pass variable value's to new Screen....
from kivymd.app import MDApp
from kivy.uix.screenmanager import Screen,ScreenManager
from kivy.lang import Builder
from kivymd.uix.list import OneLineListItem
#Builder String
helper_string = '''
ScreenManager:
Hello:
Bye:
<Hello>:
name: 'hello'
ScrollView:
MDList:
id: list
<Bye>:
name: 'bye'
MDLabel:
text:'Good Bye'
MDLabel:
id:'aaa'
text:""
'''
class Hello(Screen):
pass
class Bye(Screen):
pass
sm = ScreenManager()
sm.add_widget(Hello(name = 'hello'))
sm.add_widget(Bye(name = 'bye'))
class DemoApp(MDApp):
def build(self):
screen = Screen()
self.help_str = Builder.load_string(helper_string)
screen.add_widget(self.help_str)
return screen
def on_start(self):
for i in range(50):
item = OneLineListItem(text='Item ' + str(i),
on_release=lambda x, value_for_pass={i}: self.passValue(value_for_pass)
)
self.help_str.get_screen('hello').ids.list.add_widget(item)
def passValue(self, *args):
args_str = ','.join(map(str,args))
print(args_str)
self.help_str.get_screen('bye').manager.current = 'bye' #how to pass/send args_str's value to bye screen???
DemoApp().run()
Since It's not clear exactly where in your screen Bye you want some variable to be passed, let's suppose you want to pass a list's text to the MDLabel having text 'Good Bye' of the screen Bye by method passValue.
You may achieve this as follows:
First in the kvlang of screen Bye assign an id say, target to the MDLabel,
<Bye>:
name: 'bye'
MDLabel:
id: target
text:'Good Bye'
Then in your method passValue,
def passValue(self, *args):
args_str = ','.join(map(str,args))
print(args_str)
bye_screen = self.help_str.get_screen('bye')
bye_screen.manager.current = 'bye'
bye_screen.ids.target.text = args_str
As a side note you perhaps don't need (as you already defined that in kvlang) the following:
sm = ScreenManager()
sm.add_widget(Hello(name = 'hello'))
sm.add_widget(Bye(name = 'bye'))
I am trying to use Kivy to create an interface. But when I try to show the text of a variable (result) it doesn't show it. Here the code:
from kivymd.app import MDApp
from kivy.lang import Builder
from covid import Covid
covid = Covid(source='worldometers')
data = covid.get_status_by_country_name('Italy')
for k in data:
result = k+str(data[k])
KV = '''
Screen:
Label:
text: result
pos_hint: {'center_x': 0.5, 'center_y': 0.5}
'''
class MainApp(MDApp):
def build(self):
self.title = "Covid"
self.theme_cls.theme_style = "Dark" # Light
self.theme_cls.primary_palette = "Red"
return Builder.load_string(KV)
MainApp().run()
I'm sorry for my english but I'm Italian then I'm not very good.
Good day. Kivy is an App framework. You need to create an entire App class and build your logic into the App.
I recommend that after you create the App class, instantiate it, run it, then run your logic code in your App.
kv script:
Screen:
MDRectangleButton:
on_release: app.calculate_result_callback
In Python:
import .......
data = covid.get_status_by_country_name('Italy')
covid = Covid(source='worldometers')
def calculate_result():
result = ""
for k in data:
result += k+str(data[k])
return result
class MyApp(App):
def calculate_result_callback(self, instance, *a):
result = calculate_result()
instance.text = result
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 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
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)