displaying a variable in a popup window with kivy - python

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.

Related

Kivy: how to access IDs created in python code

I have this code below. I've set id by python code, but I couldn't access.
def abrirReceita(self,instance):
instance.text = str(instance.ids)
I'd like to change the text with the number of the ID when I press.
Exemple: if I input the first button, change the text for '1', which is the ID I've passed.
from kivymd.app import MDApp
from kivymd.uix.boxlayout import BoxLayout
from kivymd.uix.floatlayout import FloatLayout
from kivymd.uix.list import TwoLineListItem
from kivymd.uix.textfield import MDTextField
from kivy.lang import Builder
import os
from kivy.core.window import Window
import sqlite3
KV = '''
ScreenManager:
Screen:
name: 'telaSelecionada'
BoxLayout:
orientation: 'vertical'
MDToolbar:
id: tb
title: 'Drinks'
md_bg_color: 0, 0, 0, 1
TelaSelecionada:
id: telaselecionada
<TelaSelecionada>:
ScrollView:
MDList:
id: mostraReceita
padding: '20dp'
'''
Window.softinput_mode = "below_target"
class TelaSelecionada(FloatLayout):
pass
class Aplicativo(MDApp):
def build(self):
return Builder.load_string(KV)
def on_start(self):
i = 1
for x in range(5):
self.textLine = TwoLineListItem(text = 'change text', secondary_text = 'change text')
self.root.ids.telaselecionada.ids.mostraReceita.add_widget(self.textLine)
self.root.ids.telaselecionada.ids.mostraReceita.ids[i] = self.textLine
self.textLine.bind(on_release = self.abrirReceita)
i += 1
def abrirReceita(self,instance):
instance.text = str(instance.ids)
Aplicativo().run()
How do I access the IDs from python code?
I'd like to change the text with the number of the ID when I press.
Just pass the required args through method abrirReceita using functools.partial as,
def on_start(self):
...
self.textLine.bind(on_release = partial(self.abrirReceita, i))
i += 1
# Then in `abrirReceita` :
def abrirReceita(self, id_index, instance):
instance.text = str(id_index)
Note:
The ids are not used here at all (actually you don't need that here for this purpose) !
Update:
As, the Widget.id has been deprecated since version 2.0.0 you should use it only in kvlang not in python.
But that doesn't keep you from creating it as a dynamically added attribute. Thus you can do something like this (I modified the on_start method a little):
def on_start(self):
mostraReceita = self.root.ids.telaselecionada.ids.mostraReceita
for i, _ in enumerate(range(5), start=1):
# Or just,
# for i in range(1, 5+1):
self.textLine = TwoLineListItem(
text = 'change text',
secondary_text = 'change text',
)
self.textLine.index = i
# Or even,
# self.textLine.id = i
self.textLine.bind(on_release = self.abrirReceita)
mostraReceita.add_widget(self.textLine)
def abrirReceita(self,instance):
instance.text = str(instance.index) # or, str(instance.id)

how to have unfocus event in kivy text Input

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..

Catch value from listitembutton to textinput kivy/python

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

How to dynamically update markup text in kivy modalview

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)

Popup and the corrupted table showing in kivy

I'm a newbie in Python and Kivy as well, so I have some trouble.
When I use kivy popup with showing the table (using "PrettyTable" module) I get broken view of this table.
My python code:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from prettytable import PrettyTable
class GeneralForm(BoxLayout):
def RUN(self):
def TABLE():
x = PrettyTable(["City name", "Area", "Population"])
x.align["City name"] = "l" # Left align city names
x.padding_width = 1 # One space between column edges and contents (default)
x.add_row(["Adelaide",1295, 1158259])
x.add_row(["Brisbane",5905, 1857594])
return str(x)
popup = Popup(title='Test popup', content=Label(text=TABLE()), auto_dismiss=False)
popup.open()
class TimeTable(App):
def build(self):
return GeneralForm()
if __name__ == '__main__':
TimeTable().run()
My .kv code:
<GeneralForm>:
orientation: "vertical"
BoxLayout:
Button:
id: but
text: "Show!"
on_press: root.RUN()
Your problem is that the default label font is not a monospace font, where every character has the same width. You can instead set the font_name property to one that is. Possibly just 'DroidSansMono' will work, using the mono font kivy bundles.

Categories

Resources