Python / Kivy: conditional design in .kv file

2024/9/19 9:35:19

Would an approach similar to the example below be possible in Kivy?
The code posted obviously doesn't work, and again it's only an example: I will need different layouts to be drawn depending on a certain property.

How would you suggest working this out?

BoxLayout:number: 0if self.number > 3:Label:text: 'number is bigger than 3'Button:text: 'click here to decrease'on_press: root.number -= 1else:Label:text: 'number is smaller than 3'Button:text: 'click here to increase'on_press: root.number += 1
Answer

KV lang has only a limited functionality, so if you want more control you should put your logic in the Python code. For example you can move your layouts into separate widgets and then dynamically select proper one from Python code with add_widget() and remove_widget().

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import NumericProperty
from kivy.lang import BuilderBuilder.load_string('''
<SubWidget1>:Label:text: 'number is bigger than 3'Button:text: 'click here to decrease'on_press: root.parent.number -= 1<SubWidget2>:Label:text: 'number is smaller than 3'Button:text: 'click here to increase'on_press: root.parent.number += 1<MyWidget>number: 0
''')class SubWidget1(BoxLayout):passclass SubWidget2(BoxLayout):passclass MyWidget(BoxLayout):number = NumericProperty()def __init__(self, *args):super(MyWidget, self).__init__(*args)self.widget = Noneself._create_widget()def _create_widget(self):print(self.number)if self.widget is not None:self.remove_widget(self.widget)if self.number > 3:self.widget = SubWidget1()else:self.widget = SubWidget2()self.add_widget(self.widget)def on_number(self, obj, value):self._create_widget()class MyApp(App):def build(self):return MyWidget()if __name__ == '__main__':MyApp().run()
https://en.xdnf.cn/q/72653.html

Related Q&A

z-axis scaling and limits in a 3-D scatter plot

I performed a Monte Carlo inversion of three parameters, and now Im trying to plot them in a 3-D figure using Matplotlib. One of those parameters (Mo) has a variability of values between 10^15 and 10^2…

How to fix value produced by Random?

I got an issue which is, in my code,anyone can help will be great. this is the example code.from random import * from numpy import * r=array([uniform(-R,R),uniform(-R,R),uniform(-R,R)])def Ft(r):f…

Can I safely assign to `coef_` and other estimated parameters in scikit-learn?

scikit-learn suggests the use of pickle for model persistence. However, they note the limitations of pickle when it comes to different version of scikit-learn or python. (See also this stackoverflow qu…

How to update the filename of a Djangos FileField instance?

Here a simple django model:class SomeModel(models.Model):title = models.CharField(max_length=100)video = models.FileField(upload_to=video)I would like to save any instance so that the videos file name …

CSS Templating system for Django / Python?

Im wondering if there is anything like Djangos HTML templating system, for for CSS.. my searches on this arent turning up anything of use. I am aware of things like SASS and CleverCSS but, as far as I …

How to use chomedriver with a proxy for selenium webdriver?

Our network environment using a proxy server to connect to the outside internet, configured in IE => Internet Options => Connections => LAN Settings, like "10.212.20.11:8080".Now, Im…

django application static files not working in production

static files are not working in production even for the admin page.I have not added any static files.I am having issues with my admin page style.I have followed the below tutorial to create the django …

Celery task in Flask for uploading and resizing images and storing it to Amazon S3

Im trying to create a celery task for uploading and resizing an image before storing it to Amazon S3. But it doesnt work as expected. Without the task everything is working fine. This is the code so fa…

Python logger formatting is not formatting the string

Following are the contents of mylogger.py:def get_logger(name=my_super_logger):log = logging.getLogger(name)log.setLevel(logging.DEBUG)formatter = logging.Formatter(fmt=%(asctime)s %(name)s %(message)s…

Python subprocess.Popen.wait() returns 0 even though an error occured

I am running a command line utility via Pythons subprocess module. I create a subprocess.Popen() object with the command line arguments and stdout=subprocess.PIPE and then I use subprocess.wait() to w…