英文:
In a Kivy form, how to add a new button dinamically to RecycleView using Python3?
问题
以下是您的代码的翻译部分:
我有一个带有一个Recycleview的Kivy表单。我想通过点击一个简单的按钮来动态添加一个按钮到我的Recycleview中。
我的Python3脚本:
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.recycleview import RecycleView
class RV(RecycleView):
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.data = []
class app(App):
rv = RV()
def build(self):
return Builder.load_file('lab.kv')
def add_to_rv(self):
self.rv.data.append('ok')
# 我应该使用哪个命令来在Recycleview中显示新按钮和新数据?
app().run()
我的kv文件:
BoxLayout:
RV:
id: rv
viewclass: 'Button'
RecycleBoxLayout:
default_size: None, dp(56)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
Button:
text: '添加到RV'
on_press: app.add_to_rv()
英文:
I have a Kivy form with one Recycleview. I would dinamically add a button to my Recycleview, by clicking a simple Button.
My Python3 script:
from kivy.app import App
from kivy.lang.builder import Builder
from kivy.uix.recycleview import RecycleView
class RV(RecycleView):
def __init__(self, **kwargs):
super(RV, self).__init__(**kwargs)
self.data=[]
class app(App):
rv=RV()
def build(self):
return Builder.load_file('lab.kv')
def add_to_rv(self):
self.rv.data.append('ok')
# which command i should use to show new button in recycleview with new data?
app().run()
My kv file:
BoxLayout:
RV:
id:rv
viewclass:'Button'
RecycleBoxLayout:
default_size: None, dp(56)
default_size_hint: 1, None
size_hint_y: None
height: self.minimum_height
orientation: 'vertical'
Button:
text:'ADD TO RV'
on_press:app.add_to_rv()
答案1
得分: 1
你的add_to_rv()
方法正在向self.rv
的数据中添加内容。但是,self.rv
是在以下语句中定义的:
rv=RV()
这会创建一个新的RV
实例。然而,在你的GUI中没有使用这个RV
实例。在你的GUI中显示的RV
实例是通过以下代码行构建的:
return Builder.load_file('lab.kv')
这两个实例没有关联。修复方法是在你的add_to_rv()
方法中访问正确的RV
实例,如下所示:
def add_to_rv(self):
self.root.ids.rv.data.append({'text': 'ok'})
另外,请注意,data
是一个包含字典的列表。你可以省略rv=RV()
这一行。
英文:
Your add_to_rv()
method is adding to the data of self.rv
. But self.rv
is defined in the statement:
rv=RV()
which creates a new instance of RV
. However, that instance of RV
is not used in your GUI. The instance of RV
that is displayed in your GUI is built by the line of code:
return Builder.load_file('lab.kv')
And those two instances are not related. The fix is to access the correct instance of RV
in your add_to_rv()
method like this:
def add_to_rv(self):
self.root.ids.rv.data.append({'text': 'ok'})
Also, note that the data
is a list of dictionaries. And you can eliminate the rv=RV()
line.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论