Python|轮播小部件在 Kivy 中使用 .kv 文件
Kivy 是Python中一个独立于平台的 GUI 工具。因为它可以在Android、IOS、Linux和Windows等平台上运行。它基本上是用来开发Android应用程序的,但这并不意味着它不能在Desktops应用程序上使用。
???????? Kivy Tutorial – Learn Kivy with Examples.
轮播小部件:
轮播小部件提供经典的移动友好轮播视图,您可以在其中滑动幻灯片。您可以将任何内容添加到轮播并使其水平或垂直移动。轮播可以按顺序或循环显示页面。要使用此小部件,您必须导入:
from kivy.uix.carousel import Carousel
Basic Approach:
1) import kivy
2) import kivy App
3) import Gridlayout
4) import Carousel
5) set minimum version(optional)
6) Create as much as widget class as needed
7) create the App class
8) return the widget/layout etc class
9) Create Carousel.kv file:
1) Create button( or what is needed)
2) Arrange the on_release / on_press function
10) Run an instance of the class
在下面的示例中,我们正在 App 中创建按钮。在此我们使用了 load_previous() 和 load_next() 函数。
load_next(mode=’next’) Animate to the next slide. load_previous() Animate to the previous slide.
方法的实现: main.py 文件:
Python3
# Program to explain how to add carousel in kivy
# import kivy module
import kivy
# base Class of your App inherits from the App class.
# app:always refers to the instance of your application
from kivy.app import App
# this restrict the kivy version i.e
# below this kivy version you cannot
# use the app or software
kivy.require('1.9.0')
# The Carousel widget provides the
# classic mobile-friendly carousel
# view where you can swipe between slides
from kivy.uix.carousel import Carousel
# The GridLayout arranges children in a matrix.
# It takes the available space and
# divides it into columns and rows,
# then adds widgets to the resulting “cells”.
from kivy.uix.gridlayout import GridLayout
# Create the Layout Class
class Carousel(GridLayout):
pass
# Create the App class
class CarouselApp(App):
def build(self):
# Set carousel widget as root
root = Carousel()
# for multiple pages
for x in range(10):
root.add_widget(Carousel())
return root
# run the App
if __name__ == '__main__':
CarouselApp().run()
Python3
# Carousel.kv file of the code
# Carousel Creation
:
rows: 2
# It shows the id which is different for different pages
Label:
text: str(id(root))
# This button will take you directly to the 3rd page
Button
text: 'load(page 3)'
on_release:
carousel = root.parent.parent
carousel.load_slide(carousel.slides[2])
# load_previous() is used to go back to previous page
Button
text: 'prev'
on_release:
root.parent.parent.load_previous()
# load_next() is used to go to next page
Button
text: 'next'
on_release:
root.parent.parent.load_next()
轮播.kv文件:
Python3
# Carousel.kv file of the code
# Carousel Creation
:
rows: 2
# It shows the id which is different for different pages
Label:
text: str(id(root))
# This button will take you directly to the 3rd page
Button
text: 'load(page 3)'
on_release:
carousel = root.parent.parent
carousel.load_slide(carousel.slides[2])
# load_previous() is used to go back to previous page
Button
text: 'prev'
on_release:
root.parent.parent.load_previous()
# load_next() is used to go to next page
Button
text: 'next'
on_release:
root.parent.parent.load_next()
输出: