我正在使用python 3.5和Kivy编写一个简单的时钟程序。
我需要列出员工,以便他们可以被选中,这样无论谁做工资单都可以了解员工的工作时间。
我已经查看了TreeView
和RecycleView
的文档,但在.kv
文件中使用它们时,我似乎无法绕过其中任何一个。< / p>
那里有什么好的例子吗?我对Kivy很新,所以也许我错过了什么?我似乎无法找到关于这个主题的任何内容,除了“它比它需要的更复杂,没有人知道它是如何工作的。”
以下是我使用TreeView
采用的一种方法,但我无法在TreeViewLabel
s上的文本中应用颜色。基本上,我刚刚基于TreeView
和TreeViewLabel
类创建了新类:
class CustomTreeViewLabel(TreeViewLabel):
"""
Custom TreeViewLabel for attaching database model instances to a node.
"""
def __init__(self, user=None, **kwargs):
super(CustomTreeViewLabel, self).__init__(**kwargs)
self.user = user
class CustomTreeView(FloatLayout):
"""
The CustomTreeView is what is used in place of a TreeView since they are useless
inside of the .kv files.
"""
def __init__(self, **kwargs):
super(CustomTreeView, self).__init__(**kwargs)
self.selected = None
tree_view = TreeView(
hide_root=True,
indent_level=4
)
# Use Peewee ORM to grab the teams set up in database
teams = [team for team in models.Team.select().execute()]
for team in teams:
# Create a node with no parent to the TreeView
team_tree_label = TreeViewLabel(text=team.name)
tree_view.add_node(team_tree_label)
# Get users on the given team.
users = [u for u in models.User.select().where(models.User.team_id == team.id)]
for user in users:
# Add the users full name as a TreeViewLabel with the team_tree_label as the parent node.
user_text = '{} {}'.format(user.first_name, user.last_name)
tree_view.add_node(CustomTreeViewLabel(user=user, text=user_text, on_touch_up=self.touch, color=(65, 207, 63, 1)), parent=team_tree_label)
# Add the TreeView widget to the FloatLayout
self.add_widget(tree_view)
def touch(self, *args, **kwargs):
"""
Handle a touch event on a child TreeViewLabel
:param args:
:param kwargs:
:return:
"""
tree_view_label, motion = args
if tree_view_label.is_selected and self.selected != tree_view_label:
# Set the selected label
self.selected = tree_view_label
print(tree_view_label.user.id)
print(tree_view_label.text)
然后我刚刚在CustomTreeView
文件中导入.kv
并使用它:
#: import CustomTreeView views.CustomTreeView
<TimeClockApp>:
do_default_tab: False
tab_width: 200
padding: 3
TabbedPanelItem:
text: 'Time Clock'
BoxLayout:
cols: 2
CustomTreeView
GridLayout:
cols: 1
spacing: 25
padding: [50, 150, 50, 150]
BoxLayout:
orientation: 'vertical'
Label:
text: ''
Button:
size_hint: (2, .5)
text: 'Clock In'
size: (20, 20)
on_press: app.root.clock_in(*args)
Button:
size_hint: (2, .5)
text: 'Clock Out'
size: (20, 20)
对于一些应该非常简单的事情来说,这看起来有点过分,我怀疑它会很好地扩展。
我该怎么做才能解决这个问题?这是人们通常如何在Kivy中制作数据列表吗?我真的不喜欢这样做。