官术网_书友最值得收藏!

  • Kivy Cookbook
  • Hugo Solis
  • 238字
  • 2021-07-16 20:39:55

Reusing styles in multiple widgets

This recipe will teach you how to take advantage of reusing styles for different widgets, a procedure that could be useful for the scalability of a system.

Getting ready

We will use this example of a file, e8.kv, where two widgets are defined:

<MyWidget1>:
    Button: 
        on_press: self.text(txt_inpt.text) 
    TextInput: 
        id: txt_inpt 
<MyWidget2>: 
    Button: 
        on_press: self.text(txt_inpt.text) 
    TextInput: 
        id: txt_inpt

We must note that they are very similar, and actually just the name of the widget is different between them.

How to do it…

The following steps provide a way to join the two widgets:

  • Let's conserve just one of the widgets.
  • The name of the discarded widget will be added to name of the conserved widget, by separating with a comma:
    <MyWidget1,MyWidget2>:
        Button: 
            on_press: self.text(txt_inpt.text) 
        TextInput: 
            id: txt_inpt 

How it works…

In this case, by separating the class names with a comma, all the classes listed in the declaration will have the same KV properties and you could join any number of similar widgets.

There's more…

In the Python code, the widgets could do different tasks, as in the next portion of code:

class MyWidget1(Widget):
    def text(self, val):
        print('text input text is: {txt}'.format(txt=val)) 
class MyWidget2(Widget): 
    writing = StringProperty('') 
    def text(self, val): self.writing = val 

Similarly, you can join the widgets in the Kv language.

See also

If you want to get more details about widgets, see the recipes in Chapter 4, Widgets.

主站蜘蛛池模板: 江达县| 大渡口区| 饶阳县| 大化| 象州县| 洪泽县| 宁城县| 彭山县| 育儿| 南宁市| 奈曼旗| 青州市| 衡水市| 宁明县| 金昌市| 泰顺县| 环江| 长乐市| 汉中市| 淳化县| 秀山| 伊金霍洛旗| 七台河市| 凌云县| 沙坪坝区| 延川县| 克拉玛依市| 大埔区| 临漳县| 大丰市| 牡丹江市| 潜江市| 叙永县| 衡阳县| 邹平县| 桓台县| 呼伦贝尔市| 长武县| 罗定市| 三明市| 东乡族自治县|