KIVY Widget class

Widget class

Jump to API

Module: kivy.uix.widget

Added in 1.0.0

The Widget class is the base class required for creating Widgets. This widget class was designed with a couple of principles in mind:

组件类是基础类, 被需要来创造组件们。  这组件类是掺和着一些智慧里的原则被设计的。

  • Event Driven     事件驱动

  • Widget interaction is built on top of events that occur. If a property changes, the widget can respond to the change in the ‘on_<propname>’ callback. If nothing changes, nothing will be done. That’s the main goal of the Property class.
     组件相互作用 是建立在呈现的事件们之上。 如果一个属性改变, 这组件可以对 on_<propname>返回结果  里的改变做出回应。如果没啥改变,没啥可干的。那是Property类的 主要的目标。

  • Separation Of Concerns (the widget and its graphical representation)
    涉及的间隔  (这组件和它的图像的表现物)

    Widgets don’t have a draw() method. This is done on purpose: The idea is to allow you to create your own graphical representation outside the widget class. Obviously you can still use all the available properties to do that, so that your representation properly reflects the widget’s current state. Every widget has its own Canvas that you can use to draw. This separation allows Kivy to run your application in a very efficient manner.
    组件们没有一个 draw()方法。 这样干是有目的的: 这主意是来允许你来在组件类之外创造你自己个的图像表现。更显然的, 你仍然可以是用所有适合的属性来这么干,以至于你的图像表现物完全地影响着组件当前的状态。 每个组件有它自己个的Canvas 你可以用来画画。 这间隔允许Kivy来运行你的应用程序在一个非常有效率的方式。

  • Bounding Box / Collision  绑定的Box  / 抵触

    Often you want to know if a certain point is within the bounds of your widget. An example would be a button widget where you only want to trigger an action when the button itself is actually touched. For this, you can use the collide_point() method, which will return True if the point you pass to it is inside the axis-aligned bounding box defined by the widget’s position and size. If a simple AABB is not sufficient, you can override the method to perform the collision checks with more complex shapes, e.g. a polygon. You can also check if a widget collides with another widget with collide_widget().
    经常,你想来知道是不是有一个明显的一点来判断里外组件的边界。 一个例子可以是一个按钮组件在你只想来引发一个行为当这按钮它自己个是真正被触摸的。  关于这点,你可以用collide_point()方法,这方法将返回True如果这点你传给它是在 以组件的位置和大小被定义的轴对称关系盒子的条件内。 如果一个简单地AABB 是不充足的, 你可以这方法上伸展来演示这抵触检查同更多复杂的姓张, 例如: 一个多边形。 你也可以使用 collide_widget() 检查是否一个组件与另一个组件抵触 

We also have some default values and behaviors that you should be aware of:|
我们也有许多默认的值和行为 你应该了解的:

  • Widget is not a Layout: it will not change the position or the size of its children. If you want control over positioning or sizing, use a Layout.
    一个组件不是一个布局: 它将不会改变它子类的位置或者大小。 如果你想在位置和大小上有所控制,使用一个 布局Layout。

  • The default size of a widget is (100, 100). This is only changed if the parent is a Layout. For example, if you add a Label inside a Button, the label will not inherit the button’s size or position because the button is not a Layout: it’s just another Widget.
    一个组件默认的大小是(100, 100). 这只有当父类是一个布局才会改变。例如,如果你增加了一个 标签Label 在一个按钮里, 这个标签Label 将不会 继承这个按钮的大小或者位置因为这按钮不是一个布局。 它只是另外一个已组建。

  • The default size_hint is (1, 1). If the parent is a Layout, then the widget size will be the parent layout’s size.
    默认的size_hint  是 (1,1),如果父类是一个布局,然后这组件大小将是父类布局的大小。

  • on_touch_down()on_touch_move()on_touch_up() don’t do any sort of collisions. If you want to know if the touch is inside your widget, use collide_point().
    on_touch_down(), on_touch_move(), on_touch_up() 不做任何种类的抵触。  如果你想知道如果触摸是是不是在你的组件内, 用collide_point()

Using Properties  使用属性

When you read the documentation, all properties are described in the format:
当你阅读当前的文件, 所有的属性都被总体安排地设计好了。

<name> is a <property class> and defaults to <default value>.
<name> 是一个 <property class> 属性类 并且默认是 <default value>

e.g.

text is a StringProperty and defaults to ‘’.
text 是一个StringProperty 字符属性 并且默认是 ' '

If you want to be notified when the pos attribute changes, i.e. when the widget moves, you can bind your own callback function like this:
如果你想被注意当位置属性改变的时候,   当这组件移动时,你可以关联你自己个地返回功能像这样:

def callback_pos(instance, value):
    print('The widget', instance, 'moved to', value)

wid = Widget()
wid.bind(pos=callback_pos)

Read more about Properties.

Basic drawing  基础绘画

Widgets support a range of drawing instructions that you can use to customize the look of your widgets and layouts. For example, to draw a background image for your widget, you can do the following:
组件支持一个范围的画画指令, 你可以用来定制你组件和布局们的外貌。 例如:  画一个背景图片给你的组件, 你可以如下这样做:

def redraw(self, args):
    self.bg_rect.size = self.size
    self.bg_rect.pos = self.pos

widget = Widget()
with widget.canvas:
    widget.bg_rect = Rectangle(source="cover.jpg", pos=self.pos, size=self.size)
widget.bind(pos=redraw, size=redraw)

To draw a background in kv:

Widget:
    canvas:
        Rectangle:
            source: "cover.jpg"
            size: self.size
            pos: self.pos

These examples only scratch the surface. Please see the kivy.graphics documentation for more information.
这些案例仅仅是仓促写了点皮毛。 请看kivy.graphic 文档的更多的知识。

Widget touch event bubbling¶  组件触摸事件冒泡

When you catch touch events between multiple widgets, you often need to be aware of the order in which these events are propagated. In Kivy, events bubble up from the first child upwards through the other children. If a widget has children, the event is passed through its children before being passed on to the widget after it.
当你在多个组件之间抓取 触摸事件, 你经常需要意识到这些事件被传播的顺序。 在kivy里, 事件从第一个子类向上到其他的子类冒泡。 如果一个组件有子类,这事件被它的子类们已经穿过了,然后再被传给这组件。
 

在多个控件之间捕获触摸事件时,你通常需要了解这些事件传播的顺序。在Kivy中,事件是从第一个子控件开始,向上冒泡至其他子控件的。如果一个控件有子控件,那么事件会先在其子控件中传递,然后再传递给其后的控件。

简单地说,这意味着当你触摸一个包含多个子控件的控件时,首先会触发子控件的触摸事件处理函数(如果它们有定义的话),然后这些事件会“冒泡”到父控件,如果父控件也定义了相应的事件处理函数,那么这些函数也会被触发。这种机制使得开发者能够更精细地控制事件在不同层级控件中的处理逻辑

文心扩展:

会传递给最顶层的部件(在这个例子中是 MyLayout),但由于 MyLayout 没有重写 on_touch_down 方法,它会将事件传递给它的子部件。然而,由于你试图将 yourlabel 和 herlabel 添加到 label(一个 Label 部件),这些事件实际上并没有到达它们,因为 label 不是一个容器,不能包含子部件。

关于 on_touch_down 方法的返回值:

  • 如果 on_touch_down 方法返回 True,则表示该事件已被该组件消耗,并且不会继续向下(到子组件)或向上(到父组件)传播。
  • 如果 on_touch_down 方法返回 False,则表示该事件没有被该组件消耗,并且会继续传播。

注意: Label 不是容器部件,它不支持子部件

As the add_widget() method inserts widgets at index 0 by default, this means the event goes from the most recently added widget back to the first one added. Consider the following:

当 add_widget() 方法插入组件在 索引默认为0 时,这意味着这事件从最新添加的组件到第一个添加的。 看下面的代码思考:

box = BoxLayout()
box.add_widget(Label(text="a"))
box.add_widget(Label(text="b"))
box.add_widget(Label(text="c"))

The label with text “c” gets the event first, “b” second and “a” last. You can reverse this order by manually specifying the index:
有”c“文字的标签首先获得 事件, “b” 第二, “a” 最后。 你可以互换这顺序通过手动地说明索引。

box = BoxLayout()
box.add_widget(Label(text="a"), index=0)
box.add_widget(Label(text="b"), index=1)
box.add_widget(Label(text="c"), index=2)

Now the order would be “a”, “b” then “c”. One thing to keep in mind when using kv is that declaring a widget uses the add_widget() method for insertion. Hence, using
现在顺序将是"a" "b" 然后是“c”。  一个事得牢记在脑海 是当使用kv文件时, 声明一个组件使用add_widget()方法来插入。 因此, 使用:

BoxLayout:
    MyLabel:
        text: "a"
    MyLabel:
        text: "b"
    MyLabel:
        text: "c"

would result in the event order “c”, “b” then “a” as “c” was actually the last added widget. It thus has index 0, “b” index 1 and “a” index 2. Effectively, the child order is the reverse of its listed order.
会导致事件顺序 "c"  "b" 然后是  "a"  当 'c'真的是最后被添加的组件。 因为它有索引是 0, “b” 索引1,  以及 “a” 索引 2.   实际上, 子类的顺序是和它陈列的顺序是相反的。

This ordering is the same for the on_touch_move() and on_touch_up() events.
这顺序 是相同的对于 on_touch_move() 和 on_touch_up() 事件。

In order to stop this event bubbling, a method can return True. This tells Kivy the event has been handled and the event propagation stops. For example:
为了停止这事件冒泡, 一个方法可以返回True。 这告诉Kivy 这事儿已经被引用了, 并且这事不传了。  例如:

class MyWidget(Widget):
    def on_touch_down(self, touch):
        If <some_condition>:
            # Do stuff here and kill the event
            return True
        else:
            return super(MyWidget, self).on_touch_down(touch)

This approach gives you good control over exactly how events are dispatched and managed. Sometimes, however, you may wish to let the event be completely propagated before taking action. You can use the Clock to help you here:
这方法给你好的控制基于真正的如何事件们被派遣和被管理。 又是,然而, 你可能希望让事件被完整地派遣在获取行动之前。 你可以使用 Clock 在这来帮助你:

class MyWidget(Label):
    def on_touch_down(self, touch, after=False):
        if after:
            print "Fired after the event has been dispatched!"
        else:
            Clock.schedule_once(lambda dt: self.on_touch_down(touch, True))
            return super(MyWidget, self).on_touch_down(touch)

Usage of Widget.centerWidget.right, and Widget.top

A common mistake when using one of the computed properties such as Widget.right is to use it to make a widget follow its parent with a KV rule such as right: self.parent.right. Consider, for example:
一个常见的错误当使用一个被计算的属性例如: Widget.right 被用来使用它来让一个组件跟随它的父类按着KV规则 例如: 右边: self.parent.right。  值得考虑的是, 例如:

FloatLayout:
    id: layout
    width: 100
    Widget:
        id: wid
        right: layout.right

The (mistaken) expectation is that this rule ensures that wid’s right will always be whatever layout’s right is - that is wid.right and layout.right will always be identical. In actual fact, this rule only says that “whenever layout’s right changes, wid’s right will be set to that value”. The difference being that as long as layout.right doesn’t change, wid.right could be anything, even a value that will make them different.
这(错误)期望 是这规则确保 组件的右边总是无论如何在 布局的右边, 那就是wid.right 和layout.right 将总是完全相同的。 事实是,这规则总是说: 无论何时布局的右边改变, 组件的右边将被设置为其改变的值。  不同时: 只要布局的右边没改变, 组件的右边可能会是任何事儿, 甚至一个让他们不一样的值

Specifically, for the KV code above, consider the following example:
尤其是, 对以上的KV代码,看看下面的例子:

print(layout.right, wid.right)
(100, 100)
wid.x = 200
print(layout.right, wid.right)
(100, 300)

As can be seen, initially they are in sync, however, when we change wid.x they go out of sync because layout.right is not changed and the rule is not triggered.
显而易见的, 初始它们是不一样的, 然而, 当我们改变wid.x, 它们会同步因为 layout.right 是不变的并且是不犯规的。

The proper way to make the widget follow its parent’s right is to use Widget.pos_hint. If instead of right: layout.right we did pos_hint: {‘right’: 1}, then the widgets right will always be set to be at the parent’s right at each layout update.
真正的方式让组件跟随它的父母的右边是使用Widget.pos_hint   如果右边被替代, layout.right, 我们设置 pos_hint:{'right':1}, 然后组件右边将持续被设置为父类的右边每当布局改变。

APIHide Description ⇑

class kivy.uix.widget.Widget(**kwargs)

Bases: kivy.uix.widget.WidgetBase

Widget class. See module documentation for more information.

Events:

on_touch_down: (touch, )

Fired when a new touch event occurs. touch is the touch object.
当一个新的触摸事件呈现时, touch是被触摸的对象

on_touch_move: (touch, )

Fired when an existing touch moves. touch is the touch object.
当一个存在的触摸滑动时,touch 是移动的触摸对象

on_touch_up: (touch, )

Fired when an existing touch disappears. touch is the touch object.
当一个存在的触摸消失时, touch 是触摸对象

on_kv_post: (base_widget, )

Fired after all the kv rules associated with the widget and all other widgets that are in any of those rules have had all their kv rules applied. base_widget is the base-most widget whose instantiation triggered the kv rules (i.e. the widget instantiated from Python, e.g. MyWidget()).
在所有的kv规则同在这些规则被组件和所有其他的组件应用联系时, base_widget 是 最基础的组件,它的实例被引用了kv的规则 (组件从python实例化)
 

on_kv_post 事件是在所有与特定组件(widget)相关的 KV 规则(即在 .kv 文件中定义的规则)以及这些规则中引用的所有其他组件的 KV 规则都被应用之后触发的。base_widget 参数是指触发这些 KV 规则的最顶层组件(即从 Python 代码中实例化的那个组件,如 MyWidget())。

这个事件在 Kivy 1.11.0 版本中引入,它允许开发者在 KV 规则完全应用后执行一些额外的操作或初始化。

Changed in version 1.11.0.

__del__ 方法与垃圾收集   Warning

Adding a __del__ method to a class derived from Widget with Python prior to 3.4 will disable automatic garbage collection for instances of that class. This is because the Widget class creates reference cycles, thereby preventing garbage collection.
增加了一个 __del__方法到一个类被组件同Python先前的版本到3.4将自动关闭垃圾收集驱使的,为了那些个本本。  这是因为组件类创建额介绍循环, 因此 preventing garbage collection
【赘述:  就说python3.4之前的版本无法正常使用垃圾收集,所以增加了一个 __del__方法。 这是因为和组件类的循环周期相关, 因此 阻止了垃圾的收集。】
 

事件属性与 EventDispatcher
 

Changed in version 1.0.9: Everything related to event properties has been moved to the EventDispatcher. Event properties can now be used when constructing a simple class without subclassing Widget.
在1.0.9 被改变了: 每个事儿和事件属性相关的都被已到了EventDispatcher. 事件属性现在可以被使用当不Widget子类化构造一个简单地类

在 Kivy 1.0.9 版本中,与事件属性相关的所有内容都被移动到了 EventDispatcher 类中。这意味着,你现在可以在不继承 Widget 类的情况下,通过简单地构造一个类并使用 EventDispatcher 的功能来使用事件属性。这为开发者提供了更大的灵活性,允许他们在不构建完整 UI 组件的情况下处理事件。

构造器与 on_* 回调

Changed in version 1.5.0: The constructor now accepts on_* arguments to automatically bind callbacks to properties or events, as in the Kv language.
在1.5.0的改变,  构造器 接收 on_*自变数 来自动地关联返回到属性或事件的,  同Kv语言里一样


在 Kivy 1.5.0 版本中,组件的构造器(即 __init__ 方法)开始支持 on_* 参数的自动绑定。这意味着,你可以在创建组件实例时直接指定某些属性或事件的回调函数,这与在 KV 语言中定义这些回调的方式类似。这种机制为 Python 代码中的组件初始化提供了更大的便利性和可读性。

add_widget(widgetindex=0canvas=None)

Add a new widget as a child of this widget. 增加一个作为这个组件子类的新组建

Parameters:

widget: Widget

Widget to add to our list of children. 这组件增加到我们的子类列表

index: int, defaults to 0

Index to insert the widget in the list. Notice that the default of 0 means the widget is inserted at the beginning of the list and will thus be drawn on top of other sibling widgets. For a full discussion of the index and widget hierarchy, please see the Widgets Programming Guide.

New in version 1.0.5.
索引来插入组件到列表里。 注意默认是0意味着组件在列表的一开始被插入, 并且因此将是其他兄弟组件的开始。 索引和组件等级制度的一个充足的描述, 请看 Widgets Programming Guide。

canvas: str, defaults to None

Canvas to add widget’s canvas to. Can be ‘before’, ‘after’ or None for the default canvas.

New in version 1.9.0.
画布 来增加组件的画布。  可以 是'before' 'after' 或者 None 作为默认画布

扩展
请介绍一下kivy中画布的before 和after 是怎样的,以及给与一个具体案例分析学习

在Kivy框架中,Canvas是用于绘制图形和进行渲染的一个核心组件。每个Widget都拥有自己的Canvas,它实际上是一个指令的容器,这些指令定义了如何绘制Widget的外观。Canvas提供了beforeafter两个特殊的属性,允许开发者在默认的Canvas绘制之前或之后添加额外的绘制指令。

Canvas的before和after

  • canvas.before:此属性允许你在默认的Canvas绘制之前添加绘制指令。由于这些指令会先于默认的绘制发生,所以它们的内容可能会被默认的绘制内容覆盖。
  • canvas.after:此属性允许你在默认的Canvas绘制之后添加绘制指令。由于这些指令在默认的绘制之后发生,所以它们的内容会覆盖默认的绘制内容。

案例分析

以下是一个简单的案例分析,演示了如何在Kivy的Widget中使用canvas.beforecanvas.after属性:

1        定义Widget类
     首先,我们定义一个自定义的Widget类,该类将使用canvas.beforecanvas.after属性来添加绘制指令。

from kivy.app import App  
from kivy.uix.widget import Widget  
from kivy.graphics import Color, Rectangle  
  
class CustomWidget(Widget):  
    def __init__(self, **kwargs):  
        super(CustomWidget, self).__init__(**kwargs)  
          
        # 使用canvas.before添加绘制指令  
        with self.canvas.before:  
            Color(1, 0, 0, 1)  # 红色  
            Rectangle(pos=self.pos, size=(100, 100))  # 绘制一个红色的矩形  
          
        # 使用canvas.after添加绘制指令  
        with self.canvas.after:  
            Color(0, 0, 1, 1)  # 蓝色  
            Rectangle(pos=(50, 50), size=(100, 100))  # 绘制一个蓝色的矩形,位置稍微偏移

2         创建应用
接下来,我们创建一个简单的Kivy应用,并将自定义的Widget添加到应用中。

class MyApp(App):  
    def build(self):  
        return CustomWidget()  
  
if __name__ == '__main__':  
    MyApp().run()

3        运行应用
运行上述代码后,你会看到一个窗口,其中包含一个自定义的Widget。由于我们在canvas.before中绘制了一个红色的矩形,并在canvas.after中绘制了一个蓝色的矩形(位置稍微偏移),所以你会看到蓝色的矩形部分覆盖了红色的矩形。

from kivy.uix.button import Button
from kivy.uix.slider import Slider
root = Widget()
root.add_widget(Button())
slider = Slider()
root.add_widget(slider)

apply_class_lang_rules(root=Noneignored_consts={}rule_children=None)

Method that is called by kivy to apply the kv rules of this widget’s class.
方法被kivy叫来应用这些组件类的KV规则

Parameters:

root: Widget

The root widget that instantiated this widget in kv, if the widget was instantiated in kv, otherwise None.
在kv中实例化这个组件的根组件,如果这个组件是在kv问津中被实例化的,

其他情况就是None

ignored_consts: set

(internal) See apply().

rule_children: list

(internal) See apply().

This is useful to be able to execute code before/after the class kv rules are applied to the widget. E.g. if the kv code requires some properties to be initialized before it is used in a binding rule. If overwriting remember to call super, otherwise the kv rules will not be applied.
这是有用的来执行代码  在之前/之后 类kv规则被引用到这组件。  如果 kv 代码需要一些属性来初始化在它被绑定到一个规则之前。 如果覆盖记得召唤 super, 如不则kv规则将不被应用。

In the following example,

class MyWidget(Widget):
    pass

class OtherWidget(MyWidget):
    pass
 

<MyWidget>:

my_prop: some_value

<OtherWidget>:

other_prop: some_value

When OtherWidget is instantiated with OtherWidget(), the widget’s apply_class_lang_rules() is called and it applies the kv rules of this class - <MyWidget> and <OtherWidget>.
当 OtherWidget 是 同OtherWidget()实例化, 组件的apply_class_lang_rules()是被召唤的 并且它应用kv中该类的规则 - <MyWidget> 和<OtherWidget>

Similarly, when the widget is instantiated from kv, e.g.

相同的,当这组件在kv中实例化

<MyBox@BoxLayout>:
    height: 55
    OtherWidget:
        width: 124

OtherWidget’s apply_class_lang_rules() is called and it applies the kv rules of this class
 - <MyWidget> and <OtherWidget>.
OtherWidget的 apply_class_lang_rules() 是被召唤并且它运用kv的这俩类的规则

Note

It applies only the class rules not the instance rules. I.e. in the above kv example in the MyBox rule when OtherWidget is instantiated, its apply_class_lang_rules() applies the <MyWidget> and <OtherWidget> rules to it - it does not apply the width: 124 rule. The width: 124 rule is part of the MyBox rule and is applied by the MyBox’s instance’s apply_class_lang_rules().
它提供应用只有当  类规则  不是 实例规则。 在以上的在MyBox的kv案例规则中,当OtherWidget 被实例化时, 它的 apply_class_lang_rules()适用 <MyWidget>和<OtherWidget>规则, 它不适用宽度 124规则。

宽度 width :  124规则是MyBox规则一部分, 并且它以MyBox的实例apply_class_lang_rules()应用
 

Changed in version 1.11.0.

canvas = None

Canvas of the widget.

The canvas is a graphics object that contains all the drawing instructions for the graphical representation of the widget.
画布 是一个可以容纳所有用来图像画画指令绘画物的构造图像对象

There are no general properties for the Widget class, such as background color, to keep the design simple and lean. Some derived classes, such as Button, do add such convenience properties but generally the developer is responsible for implementing the graphics representation for a custom widget from the ground up. See the derived widget classes for patterns to follow and extend.
对于组件类来说,这是不常见的属性,例如背景颜色,保持设计简单和精简。 一些衍生类, 例如 Button, 添加方便的属性是负责的,但通常开发者是对执行图像绘画物定做的成组组件。看衍生组件类的模型来使用和扩展:

See Canvas for more information about the usage.

center

Center position of the widget. 组件的中心

center is a ReferenceListProperty of (center_xcenter_y) properties. 
中心 是一个列表相关(center_x, center_y)的属性

center_x

X center position of the widget.

center_x is an AliasProperty of (x + width / 2.).

alias   美/ˈeɪliəs别名

center_y

Y center position of the widget.

center_y is an AliasProperty of (y + height / 2.).

children

List of children of this widget.

children is a ListProperty and defaults to an empty list.

Use add_widget() and remove_widget() for manipulating the children list. Don’t manipulate the children list directly unless you know what you are doing.
使用 add_widget() 和 remove_widget() 来操控子类列表。 不要直接操控子类列表除非你知道你在干啥。

clear_widgets(children=None)

Remove all (or the specified) children of this widget. If the ‘children’ argument is specified, it should be a list (or filtered list) of children of the current widget.
在组件中消除所有(或者特指的)子类。 如果子类自变量是特指的, 它应该是当前组件子类的一个列表(或者被过滤过的列表) 。

Changed in version 1.8.0: The children argument can be used to specify the children you want to remove.
1.8.0的改变: 子类自变量 可以被用来特指你想移除的子类。

Changed in version 2.1.0: Specifying an empty children list leaves the widgets unchanged. Previously it was treated like None and all children were removed.
2.1.0改变: 特指一个空 子类 列表 留给 没被改变的组件部分。 以前它被当作None对待, 并且所有的子类都被消除。

cls

Class of the widget, used for styling.

collide_point(xy)

Check if a point (x, y) is inside the widget’s axis aligned bounding box.

Parameters:
x: numeric

x position of the point (in parent coordinates)

y: numeric

y position of the point (in parent coordinates)

Returns:

A bool. True if the point is inside the bounding box, False otherwise.

Widget(pos=(10, 10), size=(50, 50)).collide_point(40, 40)
True

collide_widget(wid)

Check if another widget collides with this widget. This function performs an axis-aligned bounding box intersection test by default.
检查是不是其他组件 同这个组件抵触。 这个功能执行一个轴对称绑定盒子默认相交测试。

Parameters:

wid: Widget class

Widget to test collision with.

Returns:

bool. True if the other widget collides with this widget, False otherwise.

wid = Widget(size=(50, 50))
wid2 = Widget(size=(50, 50), pos=(25, 25))
wid.collide_widget(wid2)
True
wid2.pos = (55, 55)
wid.collide_widget(wid2)
False

disabled

Indicates whether this widget can interact with input or not.
表明这个组件是否可以与 input 相互作用。

disabled is an AliasProperty and defaults to False.

Note

  1. Child Widgets, when added to a disabled widget, will be disabled automatically.
    1。  子类组件, 当被添加到一个丧失能力的组件, 将被自动地丧失能力。

  2. Disabling/enabling a parent disables/enables all of its children.
    2. 使丧失能力/使能动 一个父类  disables/enables 它所有的子类。

New in version 1.8.0.

Changed in version 1.10.1: disabled was changed from a BooleanProperty to an AliasProperty to allow access to its previous state when a parent’s disabled state is changed.
1.10.1改变:  disabled 被从一个波尔数值属性改变到了一个  别名属性 来允许进入它的先前状态当一个父类 的 disabled状态被改变时。

export_as_image(*args**kwargs)

Return an core Image of the actual widget.  返回一个真实组件的代码图片

New in version 1.11.0.

export_to_png(filename*args**kwargs)

Saves an image of the widget and its children in png format at the specified filename. Works by removing the widget canvas from its parent, rendering to an Fbo, and calling save().
以png格式在特定文件名内保存一个组件和它子类照片。 以从其父类移除组件画布为职责,呈现给一个Fbo, 并且召唤save()

Note

The image includes only this widget and its children. If you want to include widgets elsewhere in the tree, you must call export_to_png() from their common parent, or use screenshot() to capture the whole window.
图片仅包括这个组件和它的子类。 如果你想在树内包含组件的其他地方。你必须从它们常见的父类 召唤export_to_png() ,或者使用screenshot()方法来捕获整个窗口。

Note

The image will be saved in png format, you should include the extension in your filename.
图像将被以png格式保存, 在你的文件夹内你应该包括扩展名

New in version 1.9.0.

Parameters:

filename: str

The filename with which to save the png.
用来保存png图片的文件夹名字 

scale: float

The amount by which to scale the saved image, defaults to 1.
以默认到1的比例数量保存图片

New in version 1.11.0.

get_parent_window()

Return the parent window.  返回父类窗口

Returns:

Instance of the parent window. Can be a WindowBase or Widget.
父类窗口的实例。 可以是一个基础窗口 或者组件

get_root_window()

Return the root window.  返回根类窗口

Returns:

Instance of the root window. Can be a WindowBase or Widget.
根类窗口的实例。 可以是一个根类窗口 或者 组件

get_window_matrix(x=0y=0)

Calculate the transformation matrix to convert between window and widget coordinates.
计算转变模型来 窗口和组件 坐标 之间转变

Parameters:

x: float, defaults to 0

Translates the matrix on the x axis.
转变matrix 在x轴

y: float, defaults to 0

Translates the matrix on the y axis.
转变matrix 在y 轴

matrix 在kivy 是什么

在Kivy中,Matrix 通常与图形变换和渲染相关。根据参考文章,特别是参考文章4中提到的kivy.graphics.transformation.Matrix()示例,可以总结出以下几点关于Kivy中的Matrix

  1. 定义与用途
    • Matrix 是Kivy中用于图形变换的一个类,它允许开发者对图形元素(如图像、形状等)进行各种变换,如平移、旋转、缩放等。
  2. 使用场景
    • 当你需要在Kivy应用程序中动态地调整图形元素的位置、大小或方向时,Matrix 类就会非常有用。
    • 例如,你可以使用Matrix来实现一个动态的UI元素,或者创建一个可以响应用户交互(如拖拽、旋转等)的图形界面。
  3. 与Kivy的集成
    • Kivy的图形渲染系统内部使用Matrix类来处理各种图形变换。这意味着,当你在Kivy中编写代码来创建或修改图形元素时,你可能会间接或直接地使用到Matrix
  4. 相关操作
    • Matrix类提供了许多方法,用于执行各种图形变换操作。例如,identity()方法用于将矩阵重置为单位矩阵(即没有变换的状态),translate()方法用于平移变换,rotate()方法用于旋转变换,scale()方法用于缩放变换等。
  5. 示例代码
    • 在参考文章4中,有一个使用Matrix的示例代码片段,它展示了如何重置一个图形元素的变换(通过设置矩阵为单位矩阵)和可能的后续操作(尽管这部分代码在给出的片段中并未完整展示)。
  6. 与其他Kivy功能的配合
    • Matrix通常与Kivy的图形绘制和渲染功能一起使用,例如CanvasGraphics模块。这些模块提供了在Kivy应用程序中创建和显示图形元素所需的工具和API。
  7. 总结
    • 简而言之,Matrix在Kivy中是一个用于图形变换的类,它允许开发者通过编程方式动态地调整图形元素的位置、大小和方向。它是Kivy图形渲染系统的重要组成部分,并与其他图形绘制和渲染功能紧密配合。

height

Height of the widget.  组件的高度

height is a NumericProperty and defaults to 100.
高度是一个 数量属性 ,并且默认是100

Warning   警告 

Keep in mind that the height property is subject to layout logic and that this has not yet happened at the time of the widget’s __init__ method.
记住, 高度属性受 布局逻辑支配, 并且这还没发生当  组件的 __init__方法运行的时候

Warning   警告 

A negative height is not supported.
一个 负数的高度 是不被支持的  

ids   获取kv文件里的 id值

This is a dictionary of ids defined in your kv language. This will only be populated if you use ids in your kv language code.
这是一个字典, 被你的kv语言定义。 这将只是出现如果你使用ids在你的kv语言代码里。

New in version 1.7.0.

ids is a DictProperty and defaults to an empty dict {}.
ids 是一个 字典属性  并且默认值是一个空的字典{}

The ids are populated for each root level widget definition. For example:
ids 是在每个组件定义的根级层次存在的。 例如: 

# in kv
<MyWidget@Widget>:
    id: my_widget
    Label:
        id: label_widget
        Widget:
            id: inner_widget
            Label:
                id: inner_label
    TextInput:
        id: text_input
    OtherWidget:
        id: other_widget


<OtherWidget@Widget>
    id: other_widget
    Label:
        id: other_label
        TextInput:
            id: other_textinput

Then, in python:

widget = MyWidget()
print(widget.ids)
{'other_widget': <weakproxy at 041CFED0 to OtherWidget at 041BEC38>,
'inner_widget': <weakproxy at 04137EA0 to Widget at 04138228>,
'inner_label': <weakproxy at 04143540 to Label at 04138260>,
'label_widget': <weakproxy at 04137B70 to Label at 040F97A0>,
'text_input': <weakproxy at 041BB5D0 to TextInput at 041BEC00>}
print(widget.ids['other_widget'].ids)
{'other_textinput': <weakproxy at 041DBB40 to TextInput at 041BEF48>,
'other_label': <weakproxy at 041DB570 to Label at 041BEEA0>}
print(widget.ids['label_widget'].ids)
{}

motion_filter

motion   美/ˈmoʊʃ(ə)n/  位移 
Holds a dict of type_id to list of child widgets registered to receive motion events of type_id.
包含一个字典的 type_id 到 子类组件列表, 被设计来位移事件的type_id

Don’t change the property directly but use register_for_motion_event() and unregister_for_motion_event() to register and unregister for motion events. If self is registered it will always be the first element in the list.
不要直接改变属性而是使用register_for_motion_event()方法 和unregister_for_motion_event()方法来对请求事件 注册和未注册。 如果自己个是被注册它将总是列表的第一个元素。

New in version 2.1.0.

Warning

This is an experimental property and it remains so while this warning is present.
这是一个实验性的属性 并且它包含 因此这份警告是当下暂时的。

on_motion(etypeme)

Called when a motion event is received. 当一个位移事件被接受时被使唤

Parameters:

etype: str

Event type, one of “begin”, “update” or “end”
事件类型    'begin'     'update'    'end'中的一个

me: MotionEvent

Received motion event   接收位移事件

Returns:

New in version 2.1.0.

Warning

This is an experimental method and it remains so while this warning is present.

on_touch_down(touch)

Receive a touch down event.  接受一个触摸按下事件

Parameters:

touch: MotionEvent class 

Touch received. The touch is in parent coordinates. See relativelayout for a discussion on coordinate systems.
触摸被接收。 触摸是在父类的坐标。 看relativelayout  为了讨论在坐标系里。

Returns:

bool If True, the dispatching of the touch event will stop. If False, the event will continue to be dispatched to the rest of the widget tree.
布尔值 
如果为True,按下事件将被停止派遣。
如果为False,事件将被继续派件到剩下的组件树。  

on_touch_move(touch)

Receive a touch move event. The touch is in parent coordinates.
接收一个触摸滑动事件。 触摸是在父类的坐标系内。

See on_touch_down() for more information.
看 on_touch_down() 获取更多知识。

on_touch_up(touch)

Receive a touch up event. The touch is in parent coordinates.
获取一个触摸松开事件,这个触摸是在父类的坐标系内。

See on_touch_down() for more information.
看on_touch_down() 来获取更多知识。

opacity   透明度

Opacity of the widget and all its children.  组件和它所有子类的透明度

New in version 1.4.1.

The opacity attribute controls the opacity of the widget and its children. Be careful, it’s a cumulative attribute: the value is multiplied by the current global opacity and the result is applied to the current context color.
透明度属性控制着组件和它子类的透明度。  值得注意的是, 它是一个 渐增的属性: 值是一个以当前全局透明度成倍数增长的, 并且结果被应用到当前的内容颜色。

For example, if the parent has an opacity of 0.5 and a child has an opacity of 0.2, the real opacity of the child will be 0.5 * 0.2 = 0.1.
举个例子, 如果父类有一个透明度是0.5, 并且一个子类有一个透明度是0.2, 那么真正的该子类的透明度将是0.5 * 0.2 = 0.1

Then, the opacity is applied by the shader as:
接下来, 透明度被着色程序应用

frag_color = color * vec4(1.0, 1.0, 1.0, opacity);

opacity is a NumericProperty and defaults to 1.0.
透明度是一个 数量属性, 并且默认是 1.0

parent 父类

Parent of this widget. The parent of a widget is set when the widget is added to another widget and unset when the widget is removed from its parent.
这个组件的父类。  一个组件的父类被设定当这个组件被添加到另一个组建的时候, 一个组件的父类也被设定当这个组件从它的父类中被移除。

parent is an ObjectProperty and defaults to None.
父类是一个  对象属性 并且 默认是 None

pos 位置

Position of the widget.  组件的位置

pos is a ReferenceListProperty of (xy) properties.
位置  是一个  (x,y)属性的标记属性 

pos_hint

Position hint. This property allows you to set the position of the widget inside its parent layout (similar to size_hint).
位置迹象。   这个属性允许你来设定这个组件在它父类布局里的位置 

For example, if you want to set the top of the widget to be at 90% height of its parent layout, you can write:
举个例子, 如果你想设置组件的上方是它父类布局的90%高度, 你可以写:

widget = Widget(pos_hint={'top': 0.9})

The keys ‘x’, ‘right’ and ‘center_x’ will use the parent width. The keys ‘y’, ‘top’ and ‘center_y’ will use the parent height.
键 'x',  'right'  和 'center_x' 将使用父类的宽度。   

键 'y', 'top'  和'center_y'将使用父类的高度。

See Float Layout for further reference. 

Note

pos_hint is not used by all layouts. Check the documentation of the layout in question to see if it supports pos_hint.

pos_hint 并不在所有的布局中被用到的。  检查相关问题里的布局的文档来看看是否这布局支持 pos_hint

pos_hint is an ObjectProperty containing a dict. 
pos_hint 是一个 包含一个字典的对象属性。

property proxy_ref¶  proxy_ref 属性

Return a proxy reference to the widget, i.e. without creating a reference to the widget. See weakref.proxy for more information.
返回一个代理的声明到这组件。  没有创建一个声明到这个组件。  看weakref.proxy 来获取更多的知识。

New in version 1.7.2.

register_for_motion_event(type_idwidget=None)

Register to receive motion events of type_id. 注册来获取 type_id的 平移事件

Override on_motion() or bind to on_motion event to handle the incoming motion events.

覆盖 on_montion() 或者绑定 到on_motion 事件 来 操控即将到来的 平移事件。

Parameters:

type_id: str

Motion event type id (eg. “touch”, “hover”, etc.)
平移事件 类型id (例如: 'touch', 'hover' ,etc)

widget: Widget

Child widget or self if omitted
子类组件 或者 自己 如果省略的话

New in version 2.1.0.

Note

Method can be called multiple times with the same arguments.
方法可以被召唤 多次同相同的自变量

Warning

This is an experimental method and it remains so while this warning is present.
这是一个实验性的方法 并且 它 存在  因此这警告是当前的。

remove_widget(widget)¶  移除组件

Remove a widget from the children of this widget.从这组件的子类中移除一个组件

Parameters:

widget: Widget

Widget to remove from our children list. 组件来从我们的子类列表移除

from kivy.uix.button import Button
root = Widget()
button = Button()
root.add_widget(button)
root.remove_widget(button)

right

Right position of the widget. 这组件的右边位置

right is an AliasProperty of (x + width). right 是一个 (x + width)的别名属性

size

Size of the widget. 组件的大小

size is a ReferenceListProperty of (widthheight) properties.
大小是一个  (width, height)属性的  参考书目列表属性

size_hint

Size hint.

size_hint is a ReferenceListProperty of (size_hint_xsize_hint_y) properties.
size_hint 是一个 (size_hint_x, size_hint_y)属性的  参考书目列表属性

See size_hint_x for more information. 

kivy 中 size 和size_hint 有什么区别

在 Kivy 框架中,size 和 size_hint 是两个用于控制控件大小的重要属性,但它们的工作方式和目的有所不同。

  1. size:

    • size 是一个 (width, height) 的元组,直接指定了控件的宽度和高度(以像素为单位)。
    • 当你设置 size 时,你正在告诉 Kivy 控件的确切大小。
    • 如果你同时设置了 size 和 size_hintsize 将优先于 size_hint
    • 如果你在一个布局(如 BoxLayout 或 GridLayout)中设置了控件的 size,并且布局尝试根据布局规则调整控件的大小,这可能会导致冲突或不可预期的行为。
  2. size_hint:

    • size_hint 是一个 (width_hint, height_hint) 的元组,其中每个值都是一个介于 0 和 1 之间的浮点数,或者是一个表示相对大小的字符串(如 'None''100dp' 等)。
    • size_hint 用于指定控件相对于其父布局(或包含它的布局)的可用空间的大小。
    • 例如,如果 size_hint 是 (0.5, 0.3),那么控件将尝试占据其父布局宽度的 50% 和高度的 30%。
    • size_hint 在与布局一起使用时特别有用,因为布局可以根据其内部的控件和可用空间自动调整它们的大小。
    • 注意,size_hint 的效果取决于父布局如何解释和使用这些值。不是所有的布局都会完全遵守 size_hint

总结:

  • size 用于直接指定控件的确切大小(以像素为单位)。
  • size_hint 用于指定控件相对于其父布局的大小(以百分比或相对大小为单位)。
  • 在与布局一起使用时,size_hint 通常更为灵活和有用。
  • 尽量避免在同一控件上同时设置 size 和 size_hint,因为这可能会导致冲突或不可预期的行为。

size_hint_max

Maximum size when using size_hint.

size_hint_max is a ReferenceListProperty of (size_hint_max_xsize_hint_max_y) properties.

New in version 1.10.0.

size_hint_max_x

When not None, the x-direction maximum size (in pixels, like width) when size_hint_x is also not None.

Similar to size_hint_min_x, except that it sets the maximum width.

size_hint_max_x is a NumericProperty and defaults to None.

New in version 1.10.0.

size_hint_max_y

When not None, the y-direction maximum size (in pixels, like height) when size_hint_y is also not None.

Similar to size_hint_min_y, except that it sets the maximum height.

size_hint_max_y is a NumericProperty and defaults to None.

New in version 1.10.0.

size_hint_min

Minimum size when using size_hint.

size_hint_min is a ReferenceListProperty of (size_hint_min_xsize_hint_min_y) properties.

New in version 1.10.0.

size_hint_min_x

When not None, the x-direction minimum size (in pixels, like width) when size_hint_x is also not None.

When size_hint_x is not None, it is the minimum width that the widget will be set due to the size_hint_x. I.e. when a smaller size would be set, size_hint_min_x is the value used instead for the widget width. When None, or when size_hint_x is None, size_hint_min_x doesn’t do anything.

Only the Layout and Window classes make use of the hint.

size_hint_min_x is a NumericProperty and defaults to None.

New in version 1.10.0.

size_hint_min_y

When not None, the y-direction minimum size (in pixels, like height) when size_hint_y is also not None.

When size_hint_y is not None, it is the minimum height that the widget will be set due to the size_hint_y. I.e. when a smaller size would be set, size_hint_min_y is the value used instead for the widget height. When None, or when size_hint_y is None, size_hint_min_y doesn’t do anything.

Only the Layout and Window classes make use of the hint.

size_hint_min_y is a NumericProperty and defaults to None.

New in version 1.10.0.

size_hint_x

x size hint. Represents how much space the widget should use in the direction of the x axis relative to its parent’s width. Only the Layout and Window classes make use of the hint.
x size hint.  代表组件相对于它的父类宽度应该在x轴方向使用多少空间。 只有布局和窗口类 使用 hint

The size_hint is used by layouts for two purposes: 
size_hint 被布局们使用2大目的:

  • When the layout considers widgets on their own rather than in relation to its other children, the size_hint_x is a direct proportion of the parent width, normally between 0.0 and 1.0. For instance, a widget with size_hint_x=0.5 in a vertical BoxLayout will take up half the BoxLayout’s width, or a widget in a FloatLayout with size_hint_x=0.2 will take up 20% of the FloatLayout width. If the size_hint is greater than 1, the widget will be wider than the parent.
    当布局需要考虑组件在它们自己上,而不是与它的子类相关, size_hint_x 是一个直接源于其父类宽度的比例, 通常在 0.0 和 1.0之间。 例如, 一个size_hint_x=0.5的组件在一个垂直的 BoxLayout布局中将占用BoxLayout宽度的一半, 或者在FloatLayout布局中的一个size_hint_x=0.2组件将占用 这个FloatLayout 宽度的20%。  如果size_hint比1大, 这组件将比父类容器 还要更宽。

  • When multiple widgets can share a row of a layout, such as in a horizontal BoxLayout, their widths will be their size_hint_x as a fraction of the sum of widget size_hints. For instance, if the size_hint_xs are (0.5, 1.0, 0.5), the first widget will have a width of 25% of the parent width.
    当多个组件在一个布局中可以分享一行的空间时, 例如 在一个水平的BoxLayout布局, 他们的宽度将是它们的size_hint_x 作为一个组件size_hints总数的一小部分。例如,如果size_hint_xs 是(0.5, 1.0, 0.5), 第一个组件将有一个父类组件25%的宽度。

size_hint_x is a NumericProperty and defaults to 1.

size_hint_y

y size hint.

size_hint_y is a NumericProperty and defaults to 1.

See size_hint_x for more information, but with widths and heights swapped.

to_local(xyrelative=False)

Transform parent coordinates to local (current widget) coordinates.
转变父类坐标到 本地(当前组件)坐标

See relativelayout for details on the coordinate systems.

Parameters:

relative: bool, defaults to False

Change to True if you want to translate coordinates to relative widget coordinates.
如果你想转变坐标系到相关坐标系, 变为True

to_parent(xyrelative=False)

Transform local (current widget) coordinates to parent coordinates.
转换当地(当前组件)坐标到父类坐标

See relativelayout for details on the coordinate systems.

Parameters:

relative: bool, defaults to False

Change to True if you want to translate relative positions from a widget to its parent coordinates.
如果你想转变相应的位置从一个组件到它的父类坐标,

to_widget(xyrelative=False)

Convert the coordinate from window to local (current widget) coordinates.
转换坐标从window 到本地(当前组件)坐标

See relativelayout for details on the coordinate systems.

to_window(xyinitial=Truerelative=False)

If initial is True, the default, it transforms parent coordinates to window coordinates. Otherwise, it transforms local (current widget) coordinates to window coordinates.
如果to_window的值起始是True, 默认值, 它转变父类坐标到窗口坐标。
其他方面(False),它转变 本地(当前组件)坐标到窗口坐标。
 

See relativelayout for details on the coordinate systems.

top

Top position of the widget. 这组件的顶部位置

top is an AliasProperty of (y + height). top是一个 (y + height)的别名属性

unregister_for_motion_event(type_idwidget=None)

Unregister to receive motion events of type_id. 注销接收到的type_id平移活动

Parameters:

type_id: str

Motion event type id (eg. “touch”, “hover”, etc.)

widget: Widget

Child widget or self if omitted
子类组件 或者自己个 如果 此代码被省略

New in version 2.1.0.

Note

Method can be called multiple times with the same arguments.
相同的变量可以召唤多次此方法。

Warning

This is an experimental method and it remains so while this warning is present.

walk(restrict=Falseloopback=False)

Iterator that walks the widget tree starting with this widget and goes forward returning widgets in the order in which layouts display them.
遛 以这个组件开始的组件树, 并且返回组件们为了在布局中展示它们 的迭代器 。

Parameters:

restrict: bool, defaults to False

If True, it will only iterate through the widget and its children (or children of its children etc.). Defaults to False.
如果为True, 它将只重复遍历 这个组件和它的子类(或者它子类的子类)

loopback: bool, defaults to False

If True, when the last widget in the tree is reached, it’ll loop back to the uppermost root and start walking until we hit this widget again. Naturally, it can only loop back when restrict is False. Defaults to False.
如果True, 当在树中的最后的组件被抵达时, 它将回到最高的根级,并开始遛直到我们再碰这个组件。  自然而然地, 它只能回环(将数据原路返回,主要用于对通信功能的测试)当限制是False时。

Returns:

A generator that walks the tree, returning widgets in the forward layout order.
一个遛树的产生者, 返回之前布局顺序的组件们。

For example, given a tree with the following structure:

GridLayout:
    Button
    BoxLayout:
        id: box
        Widget
        Button
    Widget

walking this tree:

# Call walk on box with loopback True, and restrict False
#  召唤 沿着Box 溜达同时 回环True, 并且  封锁 False
[type(widget) for widget in box.walk(loopback=True)]
[<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>,
    <class 'Widget'>, <class 'GridLayout'>, <class 'Button'>]
# Now with loopback False, and restrict False
# 召唤 回环False, 并且 封锁False
[type(widget) for widget in box.walk()]
[<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>,
    <class 'Widget'>]
# Now with restrict True
[type(widget) for widget in box.walk(restrict=True)]
[<class 'BoxLayout'>, <class 'Widget'>, <class 'Button'>]

下面看一下文心扩展

这段文档描述了一个名为 walk 的方法,它用于遍历一个由 Kivy(一个用于开发多触摸应用的 Python 库)的组件(widget)组成的树形结构。这个方法返回一个迭代器,该迭代器会按照布局中显示组件的顺序来返回组件。

下面是参数和示例的详细解释:

参数:

  • restrict: 布尔值,默认为 False。如果设置为 True,则迭代器仅返回给定组件的直接子组件,不会继续遍历子组件的子组件。
  • loopback: 布尔值,默认为 False。如果设置为 True,则当遍历到树的末端时,迭代器会返回到根组件并继续遍历。这允许迭代器再次访问已经访问过的组件。

示例:

假设我们有以下组件树结构:

GridLayout:  
    Button  
    BoxLayout:  # id: box  
        Widget  
        Button  
    Widget

1        使用 loopback=True 和 restrict=False 遍历

# 假设 box 是上面 BoxLayout 组件的实例  
[type(widget).__name__ for widget in box.walk(loopback=True)]  
# 输出可能类似于:  
# ['BoxLayout', 'Widget', 'Button', 'Widget', 'GridLayout', 'Button']

结果会包含 BoxLayoutbox)、它的两个子组件(Widget 和 Button)、GridLayout(根组件)以及 GridLayout 的第一个子组件 Button(因为 loopback 为 True,所以迭代器在到达 GridLayout 的末尾后回到 GridLayout 并继续遍历)。

2        使用 loopback=False 和 restrict=False 遍历

# 假设 box 是上面 BoxLayout 组件的实例  
[type(widget).__name__ for widget in box.walk()]  
# 输出可能类似于:  
# ['BoxLayout', 'Widget', 'Button', 'Widget']

结果会包含 BoxLayoutbox)以及它的两个子组件(Widget 和 Button)。由于 loopback 为 False,迭代器在到达 BoxLayout 的末尾后停止。

在这个例子中,迭代器仅遍历 BoxLayout 的直接子组件,并且不会返回到 GridLayout 或继续遍历其他组件,因为 loopback 为 False

3        使用 restrict=True 遍历

# 假设 box 是上面 BoxLayout 组件的实例  
[type(widget).__name__ for widget in box.walk(restrict=True)]  
# 输出可能类似于:  
# ['BoxLayout', 'Widget', 'Button']

结果会包含 BoxLayoutbox)以及它的两个直接子组件(Widget 和 Button)。由于 restrict 为 True,迭代器不会遍历子组件的子组件。

在这个例子中,由于 restrict 为 True,迭代器仅返回 BoxLayout 的直接子组件,不会继续遍历这些子组件的子组件。

注意:在示例中,我使用了 type(widget).__name__ 而不是 type(widget) 来仅打印类名,以使输出更易于阅读。在实际的 Kivy 应用中,你可以根据需要使用 type(widget) 或其他方法来处理遍历到的组件。

kivy 中type() 是什么

在 Kivy(一个用于开发多触摸应用的 Python 库)和其他 Python 环境中,type() 是一个内置函数,用于返回对象的类型。这个函数在 Python 中是通用的,并不特定于 Kivy。

当你对一个对象使用 type() 函数时,它会返回该对象所属的类型或类的类型对象。

例如:

# 定义一个简单的字符串  
s = "Hello, World!"  
print(type(s))  # 输出: <class 'str'>  
  
# 定义一个 Kivy 的 Button  
from kivy.uix.button import Button  
b = Button(text='Click me')  
print(type(b))  # 输出: <class 'kivy.uix.button.Button'>

在上面的例子中,type(s) 返回字符串的类 <class 'str'>,而 type(b) 返回 Kivy Button 类的类 <class 'kivy.uix.button.Button'>

在 Kivy 应用中,你可能会经常使用 type() 或其他 Python 内置函数和特性来检查对象的类型、执行条件逻辑或进行其他操作。但是,要注意,尽管 type() 可以用于这些目的,但在某些情况下,使用 isinstance() 函数可能更为推荐,因为它考虑了继承关系,而 type() 只会检查直接的类型匹配。

New in version 1.9.0.

walk_reverse(loopback=False)

Iterator that walks the widget tree backwards starting with the widget before this, and going backwards returning widgets in the reverse order in which layouts display them.
从这之前组件反方向的溜达组件树迭代器, 并且向后返回组件以和布局展示它们相反方向顺序

This walks in the opposite direction of walk(), so a list of the tree generated with walk() will be in reverse order compared to the list generated with this, provided loopback is True.
这在walk()反向溜达, 因此这列表和walk()所生产的列表是反向的。

Parameters:

loopback: bool, defaults to False

If True, when the uppermost root in the tree is reached, it’ll loop back to the last widget and start walking back until after we hit widget again. Defaults to False.

Returns:

A generator that walks the tree, returning widgets in the reverse layout order.

For example, given a tree with the following structure:

GridLayout:
    Button
    BoxLayout:
        id: box
        Widget
        Button
    Widget

walking this tree:

# Call walk on box with loopback True
[type(widget) for widget in box.walk_reverse(loopback=True)]
[<class 'Button'>, <class 'GridLayout'>, <class 'Widget'>,
    <class 'Button'>, <class 'Widget'>, <class 'BoxLayout'>]
# Now with loopback False
[type(widget) for widget in box.walk_reverse()]
[<class 'Button'>, <class 'GridLayout'>]
forward = [w for w in box.walk(loopback=True)]
backward = [w for w in box.walk_reverse(loopback=True)]
forward == backward[::-1]
True

New in version 1.9.0.

width

Width of the widget.

width is a NumericProperty and defaults to 100.

Warning

Keep in mind that the width property is subject to layout logic and that this has not yet happened at the time of the widget’s __init__ method.

常记在思路中, 宽度属性是支持布局逻辑,并且当widget 初始化__init__方法时,这玩意还没发生

Warning

A negative width is not supported.

一个负数的宽度是不被支持的

x

X position of the widget.

x is a NumericProperty and defaults to 0.

y

Y position of the widget.

y is a NumericProperty and defaults to 0.

exception kivy.uix.widget.WidgetException

Bases: Exception

Fired when the widget gets an exception.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xinzheng新政

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值