Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

Dynamic Kivy Widgets All of these programs so far have had the widgets hard-coded in the kv file, but what if we want to create

Dynamic Kivy Widgets

All of these programs so far have had the widgets "hard-coded" in the kv file, but what if we want to create dynamic widgets based on a variable or the contents of a file or something?

First, open and study dynamic_widgets.py/kv in the demos to learn how to dynamically create widgets. The important aspects of this demo are:

We set an id for the BoxLayout widget that we will add items to in the kv file. Note that this cannot be the root widget!

We create the widgets (e.g., buttons) in Python code, e.g.,

temp_button = Button(text=name) 

We add these new widgets using the add_widget method, e.g.,

self.root.ids.entries_box.add_widget(temp_button) 

We bind a callback function when you make the widget object to add event handler code, e.g.,

temp_button.bind(on_release=self.press_entry) 

Something else of interest is that we dynamically set the background_color of the Buttons.

Dynamic Labels

Files: dynamic_labels.py and dynamic_labels.kv

Now it's your turn...

Create a very simple app that has a list of names (strings) and dynamically creates a separate Label for each one.

Notice some things in dynamic_widgets demo that will be very similar (but not the same) in yours:

the dictionary is defined in the init function (this is the data, or model)

the widgets (Buttons in the demo, but yours will be Labels) are made with a loop in the build function

Note: Start a new blank Python program for this; do not copy the dynamic_widgets example as it is too different. Your app won't have any buttons or interactivity. Use the example as a reference and copy small sections or ideas from it.

Here's a suggested kv file you could use. Notice how simple it is, but it does have a child BoxLayout with an id.

BoxLayout: BoxLayout: orientation: 'vertical' id: main

.kv

BoxLayout: orientation: 'vertical' BoxLayout: orientation: 'vertical' # this layout is populated with Button widgets in app code id: entries_box Label: size_hint_y: 0.1 text: app.status_text BoxLayout: orientation: 'horizontal' size_hint_y: 0.2 Button: text: "Create Widgets" on_press: app.create_widgets() Button: text: "Clear Widgets" on_press: app.clear_all()

.py

""" Kivy example for CP1404/CP5632, IT@JCU Dynamically create buttons based on content of dictionary Lindsay Ward, first version: 11/07/2016 """ from kivy.app import App from kivy.lang import Builder from kivy.uix.button import Button from kivy.properties import StringProperty NEW_COLOUR = (1, 0, 0, 1) # RGBA for red ALTERNATIVE_COLOUR = (1, 0, 1, 1) # RGBA for magenta class DynamicWidgetsApp(App): """Main program - Kivy app to demo dynamic widget creation.""" status_text = StringProperty() def __init__(self, **kwargs): """Construct main app.""" super().__init__(**kwargs) # basic data (model) example - dictionary of names: phone numbers self.name_to_phone = {"Bob Brown": "0414144411", "Cat Cyan": "0441411211", "Oren Ochre": "0432123456"} def build(self): """Build the Kivy GUI.""" self.title = "Dynamic Widgets" self.root = Builder.load_file('dynamic_widgets.kv') self.create_widgets() return self.root def create_widgets(self): """Create buttons from data and add them to the GUI.""" for name in self.name_to_phone: # create a button for each data entry, specifying the text temp_button = Button(text=name) temp_button.bind(on_press=self.press_entry) # set the button's background colour temp_button.background_color = NEW_COLOUR # add the button to the "entries_box" layout widget self.root.ids.entries_box.add_widget(temp_button) def press_entry(self, instance): """Handle pressing entry buttons.""" # get name (dictionary key) from the text of Button we clicked on name = instance.text # change the button's background colour instance.background_color = ALTERNATIVE_COLOUR # update status text self.status_text = f"{name}'s number is {self.name_to_phone[name]}" def clear_all(self): """Clear all widgets that are children of the "entries_box" layout widget.""" self.root.ids.entries_box.clear_widgets() DynamicWidgetsApp().run()

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Database Design For Mere Mortals

Authors: Michael J Hernandez

4th Edition

978-0136788041

More Books

Students also viewed these Databases questions

Question

Why are flexible resources essential to lean production?

Answered: 1 week ago