Kivy 简明教程

Kivy - Image Viewer

在本章中,我们将在 Kivy 中构建一个简单的图像查看器应用程序。下面的代码使用了 Kivy 的图像小部件和按钮来浏览选定文件夹中的图像列表。还有一个按钮,用于打开文件选择器,让用户选择不同的文件夹来查看图像。

In this chapter, we shall build a simple Image Viewer app in Kivy. The code below uses Kivy’s Image widget and buttons for navigation through the list of images in the selected folder. There is also a button which opens a FileChooser to let the user select different folder to view the images in.

首先,我们需要构建当前选定文件夹中所有图像文件列表。为此,我们使用 os.listdir() 方法。

First, we need to build a list of all the image files in the currently selected folder. We use the os.listdir() method for this purpose.

import os
self.idx=0
self.fillist=[]
dir_path = '.'
for file in os.listdir(dir_path):
   if file.endswith('.png'):
      self.fillist.append(file)

应用程序界面的构建涉及一个垂直框布局,其中图像对象位于顶部,而另一个水平框布局则包含三个按钮。

The construction of app interface involves a vertical box layout, in which the Image object is placed on top and another horizontal box layout holding three buttons.

lo=BoxLayout(orientation='vertical')
self.img= Image(source=self.fillist[self.idx])
lo.add_widget(self.img)

hlo=BoxLayout(orientation='horizontal', size_hint=(1, .1))
self.b1 = Button(text = 'Dir', on_press=self.onButtonPress)
self.b2 = Button(text = 'Prev', on_press=self.previmg)
self.b3 = Button(text = 'Next', on_press=self.nextimg)

hlo.add_widget(self.b1)
hlo.add_widget(self.b2)
hlo.add_widget(self.b3)
lo.add_widget(hlo)

Image 组件首先显示第一个可用图像。当标有“下一步”的按钮被单击时,指向文件列表的索引递增;当单击“上一步”按钮时,它递减,在图像对象中加载索引图像文件。

The Image widget displays the first available image to start with. When the button captioned "Next" is clicked, the index pointing to the filelist is incremented; and when the "Previous" button is clicked, it is decremented, loading the indexed image file in the Image object.

def previmg(self, instance):
   self.idx-=1
   if self.idx<0: self.idx=0
   self.img.source=self.fillist[self.idx]

def nextimg(self, instance):
   self.idx+=1
   if self.idx>=len(self.fillist):
self.idx=len(self.fillist)-1
   self.img.source=self.fillist[self.idx]

第三个按钮(带说明的 Dir)弹出一个文件选择器对话框。您可以选择要查看的所需文件夹。

The third button (captioned Dir) pops up a FileChooser dialog. You can choose the required folder to view.

def onButtonPress(self, button):
   layout=GridLayout(cols=1)
   fw=FileChooserListView(dirselect=True, filters=["!*.sys"])
   fw.bind(on_selection=self.onselect)
   closeButton = Button(
      text = "OK", size_hint=(None, None),
      size=(100,75)
   )
   layout.add_widget(fw)
   layout.add_widget(closeButton)
   self.popup = Popup(
      title='Choose Folder', content=layout,
      auto_dismiss=False, size_hint=(None, None),
      size=(400, 400)
   )
   self.popup.open()

Example

当前文件夹中的图像是开始填充文件列表。以下是可以提供的完整代码:

Images in the current folder populate the fillist to start with. Here is the complete code −

from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.popup import Popup
from kivy.uix.image import Image
from kivy.uix.button import Button
from kivy.uix.filechooser import FileChooserListView
from kivy.core.window import Window

Window.size = (720, 400)

class ImageViewerApp(App):
   def previmg(self, instance):
      self.idx -= 1
      if self.idx < 0: self.idx = 0
      self.img.source = self.fillist[self.idx]

   def nextimg(self, instance):
      self.idx += 1
      if self.idx >= len(self.fillist): self.idx = len(self.fillist) - 1
      self.img.source = self.fillist[self.idx]

   def onButtonPress(self, button):
      layout = GridLayout(cols=1)
      fw = FileChooserListView(dirselect=True, filters=["!*.sys"])
      fw.bind(on_selection=self.onselect)
      closeButton = Button(
         text="OK", size_hint=(None, None), size=(100, 75)
      )
      layout.add_widget(fw)
      layout.add_widget(closeButton)
      self.popup = Popup(
         title='Choose Folder', content=layout,
         auto_dismiss=False, size_hint=(None, None), size=(400, 400)
      )
      self.popup.open()
      closeButton.bind(on_press=self.on_close)

   def onselect(self, *args):
      print(args[1][0])

   def on_close(self, event):
      self.popup.dismiss()

   def build(self):
      import os
      self.idx = 0
      self.fillist = []
      dir_path = '.'
      for file in os.listdir(dir_path):
         if file.endswith('.png'):
            self.fillist.append(file)
      lo = BoxLayout(orientation='vertical')
      self.img = Image(source=self.fillist[self.idx])
      lo.add_widget(self.img)

      hlo = BoxLayout(orientation='horizontal', size_hint=(1, .1))

      self.b1 = Button(text='Dir', on_press=self.onButtonPress)
      self.b2 = Button(text='Prev', on_press=self.previmg)
      self.b3 = Button(text='Next', on_press=self.nextimg)
      hlo.add_widget(self.b1)
      hlo.add_widget(self.b2)
      hlo.add_widget(self.b3)
      lo.add_widget(hlo)
      return lo
ImageViewerApp().run()

Output

运行此代码时,它将显示索引“0”处的图像:

When you run this code, it will display the image at index "0" −

kivy image viewer

单击导航按钮向前或向后。单击“目录”按钮选择一个新文件夹。

Click the navigation buttons to go forward and back. Click the "Dir" button to select a new folder.

kivy navigation buttons