如何设置由tkinter filechooser选择的文件(图像)作为Kivy图像小部件的源?

时间:2018-07-21 17:05:23

标签: python image kivy filechooser

我目前正在学习Kivy,我正在使用tkinter filechooser浏览存储在计算机上的图像,并希望将所选图像设置为“图像”小部件的源。

下面的代码在单击按钮时启动tkinter filechooser,我应该如何将获取的文件设置为图像小部件的源。谢谢您的宝贵时间。

main.py

document.getElementById , document.getElementsByClassName , document.querySelector

sample.kv

from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.uix.popup import Popup
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty

from tkinter.filedialog import askopenfilename
from tkinter import Tk

class SampBoxLayout(BoxLayout):
# Defines two FileChoosers.

    def get_image_one(self):
        # Select image file types, returned image should be used as source of Image widget.
        Tk().withdraw() # avoids window accompanying tkinter FileChooser
        img1 = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
        return img1

    def get_image_two(self):
        Tk().withdraw()
        img2 = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
        return img2

class SampleApp(App):
    def build(self):
        # Set the background color for the window
        Window.clearcolor = (1, 1, 1, 1)
        return SampBoxLayout()

sample_app = SampleApp()
sample_app.run()

1 个答案:

答案 0 :(得分:0)

解决方案是ColoredBackground可以在get_image_oneget_image_two中访问,为此我们可以做以下属性:

*。kv

...
<SampBoxLayout>:
    first_image: first_image     # <----
    second_image: second_image   # <----
    orientation: "vertical"
    padding: 10
    spacing: 10

    # ---------- Button FileChooser ----------
    BoxLayout:
        ...

    # ---------- Display Images----------
    BoxLayout:
        orientation: "horizontal"
        height: 30

        ColoredBackground:
            id: first_image  # <----
            size: self.parent.width, self.parent.height
            allow_stretch: True
            keep_ratio: False

        ColoredBackground:
            id: second_image  # <----
            size: self.parent.width, self.parent.height
            allow_stretch: True
            keep_ratio: False

*。py

def get_image_one(self):
    # Select image file types, returned image should be used as source of Image widget.
    Tk().withdraw() # avoids window accompanying tkinter FileChooser
    img = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
    self.first_image.source = img

def get_image_two(self):
    Tk().withdraw()
    img = askopenfilename(initialdir = "/",title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
    self.first_image.source = img