如何在每次数据变化时刷新kivy RecycleView?

2024-03-29

我正在尝试创建一个简单的考勤应用程序。

程序启动时,所有标签都在取消选择列表中

预期行为:当选择任何标签时,数据将移动到所选列表,现在所选标签位于连接列表的末尾。然后 RecycleView 刷新以显示此更改。

所以我设法使数据从一个列表移动到另一个列表,但我无法使 RecycleView 刷新

我尝试使用 ids 但失败了

我希望有一个人可以帮助我。我认为这对于有知识的人来说是一个常规问题,但对于像我这样的菜鸟来说却不是。

我是第一次在这个网站上提问,所以提前抱歉

这是代码:

from kivy.app import App
from kivy.lang import Builder
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.recycleview import RecycleView
from kivy.uix.recycleview.views import RecycleDataViewBehavior
from kivy.uix.label import Label
from kivy.properties import BooleanProperty
from kivy.properties import ListProperty
from kivy.uix.recycleboxlayout import RecycleBoxLayout
from kivy.uix.behaviors import FocusBehavior
from kivy.uix.recycleview.layout import LayoutSelectionBehavior
from datetime import datetime
import kivy
from kivy.config import Config
Config.set('graphics', 'width', '300')
Config.set('graphics', 'height', '500')

importedlist = ['Novella Varela', 'Caroll Faircloth', 'Douglas Schissler',
                'Rolande Hassell', 'Hayley Rivero', 'Niesha Dungy', 'Winfred Dejonge', 'Venetta Milum']
deselected_list = importedlist[:]
selected_list = []

class SelectableRecycleBoxLayout(FocusBehavior, LayoutSelectionBehavior,
                                 RecycleBoxLayout):
    ''' Adds selection and focus behaviour to the view. '''

class SelectableLabel(RecycleDataViewBehavior, Label):
    ''' Add selection support to the Label '''
    index = None
    selected = BooleanProperty(False)
    selectable = BooleanProperty(True)

    def refresh_view_attrs(self, rv, index, data):
        ''' Catch and handle the view changes '''
        self.index = index
        return super(SelectableLabel, self).refresh_view_attrs(
            rv, index, data)

    def on_touch_down(self, touch):
        ''' Add selection on touch down '''
        if super(SelectableLabel, self).on_touch_down(touch):
            return True
        if self.collide_point(*touch.pos) and self.selectable:
            return self.parent.select_with_touch(self.index, touch)

    def apply_selection(self, rv, index, is_selected):
        ''' Respond to the selection of items in the view.
        and add/remove items from lists
        '''
        self.selected = is_selected
        if self.selected and self.text in deselected_list:
            selected_list.append(self.text)
            deselected_list.remove(self.text)
            print(selected_list)
        elif not self.selected and self.text in selected_list:
            deselected_list.append(self.text)
            selected_list.remove(self.text)
            print(deselected_list)

class RV(RecycleView):
    # this needs to be updated every time any label is selected or deselected
    def __init__(self, **kwargs):
        super(RV, self).__init__(**kwargs)
        self.data = ([{'text': str(row)} for row in sorted(deselected_list)]
                     + [{'text': str(row)} for row in sorted(selected_list)])

class Screen(BoxLayout):
    now = datetime.now()

    def nowdate(self):
        return self.now.strftime('%d')

    def nowmonth(self):
        return self.now.strftime('%m')

    def nowyear(self):
        return self.now.strftime('%y')

    def nowhour(self):
        return self.now.strftime('%H')

    def nowminute(self):
        return self.now.strftime('%M')

Builder.load_string('''
#:import datetime datetime

<Screen>:
    orientation: 'vertical'
    BoxLayout:
        size_hint_y: None
        height: 30
        TextInput:
            id: date
            text: root.nowdate()
        TextInput:
            id: date
            text: root.nowmonth()
        TextInput:
            id: date
            text: root.nowyear()
        TextInput:
            id: date
            text: root.nowhour()
        TextInput:
            id: date
            text: root.nowminute()
        Button:
    RV:
        viewclass: 'SelectableLabel'
        SelectableRecycleBoxLayout:
            default_size: None, dp(45)
            default_size_hint: 1, None
            size_hint_y: None
            height: self.minimum_height
            orientation: 'vertical'
            multiselect: True
            touch_multiselect: True
    Button:
        size_hint_y: None
        height: 30

<SelectableLabel>:
    # Draw a background to indicate selection
    canvas.before:
        Color:
            rgba: (.0, 0.9, .1, .3) if self.selected else (0, 0, 0, 1)
        Rectangle:
            pos: self.pos
            size: self.size

''')

class TestApp(App):
    def build(self):
        return Screen()

if __name__ == '__main__':
    TestApp().run()

好吧,我确实在尝试解决这个问题时绊倒了几次,但我想我已经明白了。我所做的是创建两个回收视图和一个可以访问 ButtonBehaviors 的 CustomLabel,以便您可以使用“on_press”而不是“on_touch_down”(它在整个树中传播,而不是与元素交互)。

.py 文件:

from kivy.app import App
from kivy.uix.recycleview import RecycleView
from kivy.uix.label import Label
from kivy.uix.behaviors import ButtonBehavior
from kivy.uix.floatlayout import FloatLayout

# Create a Custom ButtonLabel that can use on_press
class ButtonLabel(ButtonBehavior, Label):

    # App.get_running_app() lets us traverse all the way through our app from
    # the very top, which allows us access to any id. In this case we are accessing
    # the content of our selected_list_view of our app
    @property
    def selected_list_content(self):
        return App.get_running_app().root.ids.selected_list.ids.content

    # And in this case, we're accessing the content of our deselected_list_view
    @property
    def deselected_list_content(self):
        return App.get_running_app().root.ids.deselected_list.ids.content

    # This is our callback that our Label's will call when pressed
    def change_location(self):

        # If the label's parent is equal* the selected list, we remove the label from its
        # parent, and then we add it to the other list
        if self.parent == self.selected_list_content:
            self.parent.remove_widget(self)
            self.deselected_list_content.add_widget(self)

        # If the label's parent is not the selected list, then it is the deselected list
        # so we remove it from its parent and add it to the selected list
        else:
            self.parent.remove_widget(self)
            self.selected_list_content.add_widget(self)

    #* Note: Kivy uses weak references. This is why we use ==, and not 'is'

# We create a CustomRecycleView that we will define in our kv file      
class CustomRecycleView(RecycleView):
    pass

class MainWindow(FloatLayout):
    pass

class ExampleApp(App):

    def build(self):
        # We create an instance of the MainWindow class, so we can access its id
        # to import our list. Otherwise we would have nothing to add the list too
        main_window = MainWindow()
        importedlist = ['Novella Varela', 'Caroll Faircloth', 'Douglas Schissler',
                'Rolande Hassell', 'Hayley Rivero', 'Niesha Dungy', 'Winfred Dejonge', 'Venetta Milum']

        # We create a Label for each Name in our imported list, and then add it
        # to the content of selected list as a default
        # I'm sure you'll be importing our own lists in a different manner
        # This is just for the example
        for name in importedlist:
            NameLabel = ButtonLabel(text=(name))
            main_window.ids.selected_list.ids.content.add_widget(NameLabel)
        return main_window

if __name__ == '__main__':
    ExampleApp().run()

kv 文件:

#:kivy 1.10.0

# We create a reference to the ButtonLabel class in our py file
<ButtonLabel>:
    # We add our callback to our ButtonLabels on press event, on_press
    on_press: root.change_location()

# We create a reference to our CustomRecycleView class in our py file
<CustomRecycleView>:
    # We create a GridLayout to store all of the content in our RecycleView
    GridLayout:
        # We give it the id content so we can define the two property values in
        # ButtonLabel class in the py file
        id: content
        size_hint_y: None

        # One column because we want it to be vertical list list
        cols: 1

        # This set up, as well as size_hint_y set to None
        # is so we can scroll vertically without issue
        row_default_height: 60
        height: self.minimum_height

<MainWindow>:
    # We then create two instances of our CustomRecycleView, give them the ids
    # referenced by the ButtonLabel methods as well as give them equal share of the
    # screen space so they do not step on each others toes
    # The canvas here is just for prototyping purposes to make sure they are the
    # properly defined sizes. You can do whatever with them you would like tbh.
    CustomRecycleView:
        id: selected_list
        size_hint: 1, .5
        pos_hint: {'x': 0, 'y': .5}
        canvas:
            Color:
                rgba: 100, 0, 0, .2
            Rectangle:
                size: self.size
                pos: self.pos
    CustomRecycleView:
        id: deselected_list
        size_hint: 1, .45
        canvas:
            Color:
                rgba: 0, 0, 100, .2
            Rectangle:
                size: self.size
                pos: self.pos
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在每次数据变化时刷新kivy RecycleView? 的相关文章

  • keras 层教程和示例

    我正在尝试编码和学习不同的神经网络模型 我对输入维度有很多复杂性 我正在寻找一些教程 显示层的差异以及如何设置每个层的输入和输出 Keras 文档 https keras io layers core 向您展示所有input shape每层
  • 如何使用 QWebView 显示 html。 Python?

    如何在控制台中显示 HTML 格式的网页 import sys from PyQt4 QtGui import QApplication from PyQt4 QtCore import QUrl from PyQt4 QtWebKit i
  • 将字段重新格式化为列,其他字段(与先前结构中成为列的字段配对)成为新列中的字段

    我的任务是清理慈善机构设计的移动应用程序中的数据 在一个部分中 用户问答应用程序使用会话由一行表示 该部分由重复的问题答案字段对组成 其中一个字段代表所提出的问题 然后它旁边的字段代表相应的答案 每个问题 字段和答案列对一起代表一个独特的问
  • 用定点迭代求解该方程

    我怎样才能解这个方程 x3 x 1 0 使用定点迭代 有没有定点迭代我可以在网上找到代码 尤其是Python 吗 Using scipy optimize fixed point http docs scipy org doc scipy
  • 从内存中发送图像

    我正在尝试为 Discord 机器人实现一个系统 该系统可以动态修改图像并将其发送给机器人用户 为此 我决定使用 Pillow PIL 库 因为它对于我的目的来说似乎简单明了 这是我的工作代码的示例 它加载一个示例图像 作为测试修改 在其上
  • 参数太少错误,同时未使用参数占位符

    我尝试使用 PYODBC 在 Access 数据库中执行 SQL 查询 但出现以下错误 pyodbc Error 07002 07002 Microsoft ODBC Microsoft Access 驱动程序 参数太少 预期为 1 301
  • pybind11:如何将 c++ 和 python 代码打包到一个包中?

    我正在尝试使用 CMake 和 pybind 11 将现有的 Python 代码和新的 C 11 代码打包在一起 我认为我缺少一些可以添加到 CMake 脚本中的简单内容 但在任何地方都找不到它 pybind11 示例只有 C 代码和没有P
  • Python 排列(包括子字符串)

    我遇到过这个帖子 如何在Python中生成列表的所有排列 https stackoverflow com questions 104420 how to generate all permutations of a list in pyth
  • python matplotlib 使用按钮事件添加和删除图形中的文本

    我试图在调用button press event 时将文本添加到鼠标指针位置的图形中 并在调用button release event 时将其删除 我已成功添加文本 但无法将其删除 这是我使用的代码的一部分 def onclick even
  • 如何在 Python for 循环中获取 GAE ndb 中当前记录的密钥?

    我目前有一个网页 其中显示数据存储中的记录列表以及编辑链接 我想从数据库转换它 至新开发银行 我是 Python 和 GAE 新手 当前代码 tbody for listtype in listtypes tr td listtype Li
  • 带有redirect_uri的social-auth-app-django Facebook后端状态

    我知道我的问题听起来像是重复的 但我到处寻找但没有找到任何解决方案 我正在努力为我的 django web 应用程序实现社交登录 到目前为止 谷歌 推特和雅虎登录均按预期工作 但facebook总是给出以下错误 URL 被阻止 此重定向失败
  • Tkinter:通过多处理启动进程会创建不需要的新窗口

    我计划围绕数值模拟编写一个小型 GUI 这就是我现在使用 Tkinter 的原因 模拟应在单独的进程中从 GUI 启动 为了玩一下 我定义了一个函数 random process 来生成成对的 randn 数字 这应该是一个真正的模拟过程
  • 在Python中将用户昵称转换为正式名字

    我正在尝试根据 Python 中的用户名字和姓氏映射来自不同系统的用户 一个问题是 名字在很多情况下都是 昵称 例如 对于用户来说 他的名字在一个系统中是 Dave 而在另一个系统中是 David python 中有没有简单的方法可以将这些
  • Python 上每个系数具有特定约束的多元线性回归

    我目前正在数据集上运行多元线性回归 起初 我没有意识到我需要限制自己的体重 事实上 我需要有特定的正权重和负权重 更准确地说 我正在做一个评分系统 这就是为什么我的一些变量应该对音符产生积极或消极的影响 然而 当运行我的模型时 结果不符合我
  • Python 用静态图像将 mp3 转换为 mp4

    我有x文件包含一个列表mp3我想转换的文件mp3文件至mp4文件带有static png photo 似乎这里唯一的方法是使用ffmpeg但我不知道如何实现它 我编写了脚本来接受输入mp3文件夹和一个 png photo 然后它将创建新文件
  • 当我移动我的 pygame 角色时,它会留下痕迹[重复]

    这个问题在这里已经有答案了 我一直在尝试用 Python 制作一个游戏 但是当我移动我的角色时 它会留下痕迹 我知道它并没有显示出那么多 但如果你靠近的话 你可以看到这条踪迹 这真的让我很困扰 这是我的代码 import pygame im
  • 使用枚举名称而不是值对 Pydantic 字段进行编码

    我有一个枚举类 class Group enum Enum user 0 manager 1 admin 2 我有一个 pydantic 模型 class User BaseModel id int username str group G
  • Spark (Python) 中的 Kolmogorov Smirnov 测试不起作用?

    我正在 Python Spark ml 中进行正态性测试 看到了我的结果think是一个错误 这是设置 我有一个标准化的数据集 范围 1 到 1 当我做直方图时 我可以清楚地看到数据不正常 gt gt gt prices norm hist
  • 通过过滤对 Pyspark Dataframe 进行分组

    我有一个数据框如下 cust id req req met 1 r1 1 1 r2 0 1 r2 1 2 r1 1 3 r1 1 3 r2 1 4 r1 0 5 r1 1 5 r2 0 5 r1 1 我必须观察客户 看看他们有多少要求 看看
  • Pandas:合并多个数据框并控制列名称?

    我想将九个 Pandas 数据帧合并到一个数据帧中 对两列进行联接 控制列名称 这可能吗 我有九个数据集 它们都有以下列 org name items spend 我想将它们加入到具有以下列的单个数据框中 org name items df

随机推荐

  • 使用curl将文件推送到GitHub存储库

    我想在 GitHub 存储库上创建 推送 新文件 而不需要git工具 因为git我的工具不可用PHP主持人 所以我做了一些研究 发现GitHub REST API https docs github com en rest 我尝试使用cur
  • 电池的最佳使用

    作为一名程序员 我可以采取哪些措施来确保我的应用程序不会占用大量资源并耗尽电池 根据您正在编写的应用程序 其中一些可能适用于您 不要使用过多的网络调用 尝试维护不经常更改的数据缓存 并且仅在上次刷新 10 秒后运行完全刷新 阻止它们向服务器
  • SQLite Swift 中有多少种方式进行 CRUD 操作?

    当我在 SQLite 中进行 CRUD 操作时 我很困惑 因为有人对我说你可以使用 FMDB 库进行 CRUD 操作 有人说 GRDB 所以 我的问题是 在 SQLite 中有多少种方法可以进行 CRUD 操作 哪种方法是正确的 我认为 G
  • 如何在 Jquery 验证中处理 html 元素 id/name 中的特殊字符?

    我有一个 HTML 表单 它在 ids 中使用特殊字符 该表单使用 JQuery 验证插件来验证用户输入 具体来说 id 包括 GUID 以下是示例代码
  • 在 Eclipse 中,Source -> Format 在“Maven Pom Editor”中被禁用

    当打开pom xml在 Eclipse 中使用 Maven Pom Editor 并切换到选项卡pom xml我无法格式化该文件 Hitting Ctrl Shift F在完全未格式化的文件中不会执行任何操作 通过上下文菜单时Source
  • Python 中的递归、记忆和可变默认参数

    Base 的意思是不只使用lru cache 所有这些都 足够快 我并不是在寻找最快的算法 但时间安排让我感到惊讶 所以我希望我能了解一些有关 Python 如何 工作 的知识 简单循环 尾递归 def fibonacci n a b 0
  • Flask 应用偶尔挂起

    我一直在开发一个 Flask 应用程序 它使用 Twilio 处理 SMS 消息 将它们存储在数据库中 并通过 JSONP GET 请求提供对前端的访问 我已经使用supervisord对其进行了守护进程 这似乎工作得很好 但每隔几天它就会
  • Erlang / Golang 端口示例中的缓冲区大小

    我有一个粗略的 Erlang to Golang 端口示例 将数据从 Erlang 传递到 Golang 并回显响应 问题是我可以传输的数据量似乎仅限于 2 8 字节 见下文 我认为问题可能出在 Golang 方面 没有创建足够大的缓冲区
  • JavaScript 中的继承和 Super

    我正在学习 JavaScript 的第三天 我遇到了这段代码 class B constructor name this name name printn return this name class A extends B constru
  • ajaxForm 错误回调内的表单对象

    我试图在 ajaxForm 的错误方法中访问我的表单对象 foo ajaxForm error function where s my foo object error 可以接受 3 个参数 但它们都不是表单对象 这也返回 url 但同样没
  • 为什么 CSS Grid 的自动填充属性在列方向上不起作用

    我正在练习用行自动填充属性 但是 它并没有按照我的意愿进行 我想创建具有高度的行minmax 140px 200px 而是获取一行高度为 200px 的行 其余行为 18px 为什么会发生这种情况 body html height 100
  • 使用ajax上传文件到远程服务器

    我对服务器端没有任何控制权 是否可以在 Iframe 中上传并加载远程服务器给出的结果 请分享一些代码 谢谢 使用名称声明 iframe 并在表单元素中定位该名称
  • 调整大小和滚动问题(JS/HTML)

    有两个容器 第一个是小视口 第二个是巨大的工作区 因此 用户滚动视口以在工作区中移动 我想通过 CSS 属性实现放大 缩小功能tranform 但是在这个过程中我遇到了一个难题 并没有找到精确的解决方案 问题是 当用户放大 缩小时 工作区中
  • 带有 @MappedSuperclass 的 Hibernate TABLE_PER_CLASS 不会创建 UNION 查询

    我正在尝试创建一系列对象 这些对象全部存储在单独的表中 但所有这些表上都有一组共同的字段 我希望 Hibernate 对所有这些表进行 UNION 但不包括超类作为表 当我用以下方式注释超类时 MappedSuperclass Inheri
  • 插入、删除、最大值 O(1)

    有人能告诉我哪种数据结构支持 O 1 的插入 删除 最大操作吗 这是一个经典的面试问题 通常是这样提出的 设计一个类似堆栈的数据结构 在 O 1 时间内执行压入 弹出和最小 或最大 操作 没有空间限制 答案是 您使用两个堆栈 主堆栈和最小
  • 在 n 维数组上使用 scipy interpn 和 meshgrid

    我正在尝试翻译大型 4D 数组的 Matlab interpn 插值 但 Matlab 和 Python 之间的公式存在显着差异 几年前有一个很好的问题 答案here https stackoverflow com questions 39
  • 如何删除R中第n个分隔符之后的所有内容?

    我有这个向量myvec 我想删除第二个 之后的所有内容并得到结果 如何删除第 n 个 之后的字符串 myvec lt c chr2 213403244 213403244 G T snp chr7 55240586 55240586 T G
  • JA017:无法查找已启动的 hadoop 作业 ID

    当我在Hue的Oozie编辑器中提交mapreduce作业时 如何解决这个问题 JA017 无法查找与操作 0000009 150711083342968 oozie root W mapreduce f660 关联的已启动 hadoop
  • WordPress 数据库中的附加表

    我正在使用 WordPress 我想为我的网站开发更多服务 我正在考虑在 WordPress 数据库中创建新表 这种方法行得通吗 我不希望 WordPress 在更新等时删除我的表 这些服务将位于单独的页面上 它们不会是 WordPress
  • 如何在每次数据变化时刷新kivy RecycleView?

    我正在尝试创建一个简单的考勤应用程序 程序启动时 所有标签都在取消选择列表中 预期行为 当选择任何标签时 数据将移动到所选列表 现在所选标签位于连接列表的末尾 然后 RecycleView 刷新以显示此更改 所以我设法使数据从一个列表移动到