I want to create a Label in my kv-file and the text I want the Label to have is supposed to be collected from my python-file. I have tried to create a function in the python-file that has a variable equal to the string I want the Label to have, but it does not seem to work and I don't know how to do it correctly...
The code below is how my kv-file looks. So it is in the field that says "text:" that I want to collect the data from my python-file.
Hope someone knows how to do!
<FirstScreen>:
GridLayout:
cols: 2
text:
In your class FirstScreen you can add a StringProperty to represent the text.
class FirstScreen(Screen):
mytext = StringProperty('default text')
Then, in your kv you can use it as:
<FirstScreen>:
Label:
text: root.mytext
Related
For example we created with kivy language simple BoxLayout1 that contains button1 and another BoxLayout2. When you click button1 it adds a new button in BoxLayout2 but it's written in python.
Is it possible to acces existing layout in kv language, in python code? Or only solution is writting whole window in python?
I couldn't find any info in kivy docs, maybe I've just missed something.
EDIT:
I've something like this
Kv:
<CreateWindow>:
BoxLayout:
Button:
text: "test"
on_release: root.press()
BoxLayout:
Label:
text: "Label"
Python:
class CreateWindow(Screen):
def press(self):
I want to add a new button near Label by activating press function
in python will be like this
class CreateWindow(Screen):
def press(self):
# the first box is the first child in the children list of the CreateWindow widget so
box1=self.children[0]
box2=self.children[1]
# and now you can decide which box you want to use add_widget method with
# in your case it should be
box2.add_widget(Button())
I am trying to use TwoLineIconListItem with add_widget in a for loop but I can't figure out how to add the icon. It does not take an Icon parameter because per the docs IconLeftWidget is nested like so:
TwoLineIconListItem:
text: "Two-line item with avatar"
secondary_text: "Secondary text here"
IconLeftWidget:
icon: "language-python"
I know how to do this in the KV language but how do you do it in a python for loop that populates a list. This is the closest I got but it puts the icon above the text
for i, z, n in zip(x[1::2], x[0::2], range(1,10)):
self.root.ids.todays_workout.add_widget(
IconLeftWidget(icon=f"numeric-{n}-box-multiple-outline"))
self.root.ids.todays_workout.add_widget(
TwoLineIconListItem(text=f"{i}", secondary_text=f"{z}"))
Perhaps a nested add_widget()? I'm not sure how to accomplish this
I think your nested add_widget() is along the right track, but you can't actually do that because add_widget() returns None. So you can do it something like this:
for i, z, n in zip(x[1::2], x[0::2], range(1,10)):
icon = IconLeftWidget(icon=f"numeric-{n}-box-multiple-outline"))
listItem = TwoLineIconListItem(text=f"{i}", secondary_text=f"{z}"))
listItem.add_widget(icon)
self.root.ids.todays_workout.add_widget(listItem)
With a second look at the docs and some help from the KivyMD support Discord Channel, I have found the solution.
You need to create a new class that inherits from the TwoLineIconListItem as such:
class ListWithIcon(TwoLineIconListItem):
icon = StringProperty("string")
Then I created a new .kv file called listwithicon.kv with the following (notice the class names match)
<ListWithIcon>:
IconLeftWidget:
icon: root.icon
Finally in my main KV string(or file) I added #: include listwithicon.kv
These steps will allow you to add an icon parameter to your function. Just be sure to pass ListWithIcon (your new class) instead of the KivyMD class TwoLineIconListItem
for i, z, n in zip(x[1::2], x[0::2], range(1,number_workouts)):
self.root.ids.todays_workout.add_widget(
ListWithIcon(text=f"{i}", secondary_text=f"{z}", icon=f"numeric-{n}-box-multiple-outline"))
I'm trying create new TabbedPanelItem with properties already created widget. But i'm getting new empty widget or replace exist.
.py
class MainScreen(Screen):
def add(self, tabbed_item):
new_tabbed_item = TabbedPanelItem()
new_tabbed_item.properties = copy(tabbed_item)
new_tabbed_item.text = "2"
self.ids.tab_panel.add_widget(new_tabbed_item)
.kv
<MainScreen>:
AnchorLayout:
canvas.before:
...
TabbedPanel:
id: tab_panel
...
TabbedPanelItem:
Button:
on_press: root.add(tab_item)
TabbedPanelItem:
id: tab_item
....
When I try to run you're code nothing pops up. You don't have enough code to test. I'm not sure what your goal is, but if you want to have a TabbedPanelItem with stuff already created without having to reproduce the same code (if that's your goal), try using #. An example: MyTabbedPanel#TabbedPanelItem:. Then you can add everything you want it to do, and reuse it instead of retyping out the code everytime.
Why does this code get a KeyError, from line #21?
I've tried different versions of similar code, but this is the only file that gets the KeyError.
Gist: https://gist.github.com/Crowbrammer/464ae3ae3ddd7d33a9eb64d856acacd0
Why is it missing the id's of each element in the Kivy file?
How come the function beneath the init() function works, with that exact same line of code--but the init() function doesn't?
I don't think record_new_model gets called.
Your constructor fails so the rest doesn't matter.
You aren't setting the ids properly.
You need to do something like this
<ModelAddLayout>:
model_add_name: model_add_name
orientation: 'vertical'
padding: 20, 20
Label:
id: title_label
text: 'Model Add Screen'
font_size: '30dp'
# text_size: '15dp'
TextInput:
id: model_add_name
text: 'Add your model name here'
multiline: False
When you are adding an id to a child it doesn't get added to the parent. You also need to add the id to the parent: model_add_name: model_add_name.
The root determines what elements get loaded into the code first.
For this code is ScreenManagement. The root for others is ModelAddLayout.
So, for the code I linked, it loads the elements of the kv file later than I expect, so there are no keys in the ids attribute to call.
What I did get to work, then, was to put everything except super() into a new function, late_init(self, keys, **largs).
After that, I put Clock.schedule_once(self.late_init, 0) after init()'s super.
This gave the app time to populate the ids, enabling my dropdown list to become a reality.
(From the comment to Radu Dita's answer.)
I was testing out Kivy's markup feature. The basic outline of my test program is there are 4 labels and a button and if the button is pressed, it changes the color of the first letter of label's text. Now, the problem is when I press the button for the first time, it changes the color of first letter of all the label's text BUT from the second press onwards, it starts adding the markup syntax in the reverse manner at the beginning of the text. This is the program:
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.lang import Builder
import string
Builder.load_string(
'''
<CLabel#Label>:
markup: True
<box>:
orientation: 'vertical'
Button:
text: 'press'
on_press: app.change()
CLabel:
id: a
text: 'abcd'
CLabel:
id: b
text: 'efgh'
CLabel:
id: c
text: 'ijkl'
CLabel:
id: d
text: 'mnop'
'''
)
class box(BoxLayout):
pass
class main(App):
def change(self):
for lol in string.lowercase[:4]:
self.root.ids[lol].text = '[color=#E5D209]{}[/color]{}'.format(self.root.ids[lol].text[0], self.root.ids[lol].text[1:])
def build(self):
return box()
if __name__ == "__main__":
main().run()
This is the output after the first press:
This is the output after the second press:
This is the output after the third press:
I hope you get the problem now. The markup syntax at the beginning of the text keeps on increasing with the number of times the button is pressed.
I thought maybe it was the loop's fault. So I removed the loop and tested with only the first widget. Same problem.
Now here's the catch- when I change the color by changing the contents of the change function like this:
def change(self):
self.root.ids.a.text = '[color=#E5D209]a[/color]bcd'
self.root.ids.b.text = '[color=#E5D209]e[/color]fgh'
self.root.ids.c.text = '[color=#E5D209]i[/color]jkl'
self.root.ids.d.text = '[color=#E5D209]m[/color]nop'
It works perfectly fine. But by doing this method, I'll have to copy paste a lot of lines. This was just a snippet of what I'm working on. The real project I'm working on has more than 15 labels and copy pasting for each and every label is tiresome. It'd be much better if it is done by a loop. It makes work short and precise.
After this, out of frustration I tried with get_color_from_hex method by this code:
self.root.ids[lol].text[0] = self.root.ids[lol].text[0].get_color_from_hex('#E5D209')
But I ended up getting an error message saying:
AttributeError: 'str' object has no attribute 'color'
I'd be really glad if someone came with a way to change the color of first letter of the text of god knows how many labels. :'(
The markup is part of the string stored in text. So the second time you run the loop, indeed the first character ([) gets inserted in between the markup tags, messing up the parsing.
What you want to do could be achieved by storing the raw text in another StringProperty, let's call it _hidden_text. Then, in the loop, you can set
self.root.ids[lol].text = '[color=#E5D209]{}[/color]{}'.format(self.root.ids[lol]._hidden_text[0], self.root.ids[lol]._hidden_text[1:])
In this way you avoid reusing the added markup.
Of course you may want to set up bindings for making the assignment _hidden_text→text automatic.
Edit:
Add this class definition:
class CLabel(Label):
hidden_text = StringProperty('')
then change the kv style for CLabel to
<CLabel>:
markup: True
text: self.hidden_text
and each use of CLabel should look like
CLabel:
id: a
hidden_text: 'abcd'