【发布时间】:2021-05-27 08:48:45
【问题描述】:
我正在尝试在 FLoatLayout 内创建一组可滑动并上下移动的小部件。但是,就像展示柜或画廊小部件一样,我似乎无法配置滑动功能。我想也许我可以使用 Carousel 小部件来实现这一点,这最终会更好,因为它具有 swiper 所需的所有功能和行为,但我无法找到让项目流血的方法因为那是我想要的样子。有没有办法可以将滑动事件绑定到我的浮动布局?我的代码:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.animation import Animation
Window.minimum_width, Window.minimum_height = Window.size
Builder.load_string('''
<Item@Button>:
size_hint: .5, .5
font_size: 32
<Swiper>:
Item:
text: "Button 1"
pos_hint: {"center_x": .5, "center_y": len(self.parent.children) * .5}
on_release: root.change_pos(self)
Item:
text: "Button 2"
pos_hint: {"center_x": .5, "center_y": (len(self.parent.children) - 1) * .5}
on_release: root.change_pos(self)
Item:
text: "Button 3"
pos_hint: {"center_x": .5, "center_y": (len(self.parent.children) - 2) * .5}
on_release: root.change_pos(self)
Item:
text: "Button 4"
pos_hint: {"center_x": .5, "center_y": (len(self.parent.children) - 3) * .5}
on_release: root.change_pos(self)
Item:
text: "Button 5"
pos_hint: {"center_x": .5, "center_y": (len(self.parent.children) - 4) * .5}
on_release: root.change_pos(self)
Item:
text: "Button 6"
pos_hint: {"center_x": .5, "center_y": (len(self.parent.children) - 5) * .5}
on_release: root.change_pos(self)
''')
class Swiper(FloatLayout):
focused_index = 0
def change_pos(self, instance):
instance_index = self.children.index(instance)
if instance_index < self.focused_index:
for item in self.children:
Animation(pos_hint={"center_y": item.pos_hint["center_y"]+.5}).start(item)
elif instance_index > self.focused_index:
for item in self.children:
Animation(pos_hint={"center_y": item.pos_hint["center_y"]-.5}).start(item)
else:
print("item already has focus")
self.focused_index = instance_index
class MainApp(App):
def build(self):
return Swiper()
if __name__ == "__main__":
MainApp().run()
【问题讨论】:
标签: python python-3.x kivy kivy-language