Kivy 简明教程
Kivy - Cache Manager
在 Kivy 框架中,Cache 类通过将一个或多个 Python 对象赋值为唯一键的值来存储它们。Kivy 的缓存管理器通过限制包含的对象数或让他们的访问保持超时限制来控制其中的对象。
In Kivy framework, the Cache class stores one or more Python objects by assigning them as value of a unique key. Kivy’s Cache manager controls the objects in it by either imposing a limit to the number of objects in it, or keeping a timeout limit to their access.
Cache 类在“kivy.cache”模块中定义。它包括静态方法:register()、append()、get() 等。
The Cache class is defined in the "kivy.cache" module. It includes the static methods: register(), append(), get(), etc.
首先,你需要通过设置对象的最大数量和超时来在缓存管理器中注册一个类别。
To start with, you need to register a Category in the Cache manager by setting the maximum number of objects and the timeout.
from kivy.cache import Cache
Cache.register(category='mycache', limit=10, timeout=5)
你现在可以最多添加 10 个 Python 对象,每个对象都有一个唯一键。
You can now add upto 10 Python objects, each with a unique key.
key = 'objectid'
instance = Label(text=text)
Cache.append('mycache', key, instance)
get() 方法从缓存中检索一个对象。
The get() method retrieves an object from the cache.
instance = Cache.get('mycache', key)
Cache 类定义了以下内容:
The Cache class defines the following methods and properties −
register() Method
此方法使用指定限制在缓存中注册一个新类别。它包含以下参数:
This method registers a new category in the cache with the specified limit. It has the following parameters −
-
category − A string identifier of the category.
-
limit − Maximum number of objects allowed in the cache. If None, no limit is applied.
-
timeout − Time after which the object will be removed from cache.
append() Method
此方法将一个新对象添加到缓存中。定义了以下参数:
This method add a new object to the cache. Following parameters are defined −
-
category − string identifier of the category.
-
key − Unique identifier of the object to store.
-
obj − Object to store in cache.
-
timeout − Time after which to object will be deleted if it has not been used. This raises ValueError if None is used as key.
get() Method
此方法用于从缓存获取对象,参数如下:
This method is used to get a object from the cache, with the following parameters −
-
category − string identifier of the category..
-
key − Unique identifier of the object in the store..
-
default − Default value to be returned if the key is not found.
Example
请看以下示例:
Take a look at the following example −
from kivy.cache import Cache
from kivy.uix.button import Button
from kivy.uix.label import Label
Cache.register(category='CacheTest', limit=5, timeout=15)
b1 = Button(text='Button Cache Test')
Cache.append(category='CacheTest', key='Button', obj=b1)
l1 = Label(text='Label Cache Test')
Cache.append(category='CacheTest', key='Label', obj=l1)
ret = (Cache.get('CacheTest', 'Label').text)
print (ret)