如何让用户选择文件作为kivy中的背景图片?

How to allow user to choose file as background image in kivy?

或者,如何使用python,给它一个ID,并将其设置为kv语言的背景图像? 我希望能够在图像而不是黑屏上绘图,我在这里这样做: 已编辑 新问题:上传按钮不起作用,这是新代码

from random import random
from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.graphics import Color, Line, Rectangle
from kivy.uix.filechooser import FileChooserListView, FileChooserIconView
from kivy.uix.floatlayout import FloatLayout

class MyPaintWidget(Widget):
    def on_touch_down(self, touch):
        color = (random(), random(), random())
        with self.canvas:
            Color(*color)
            d = 30.
            touch.ud['line'] = Line(points=(touch.x, touch.y))

    def on_touch_move(self, touch):
        touch.ud['line'].points += [touch.x, touch.y]




class MyPaintApp(App):

  def build(self):
        parent = Widget()
        painter = MyPaintWidget()
        Choose = Button(text = 'upload image')
        parent.add_widget(painter)
        parent.add_widget(Choose)


        def chooose_file(obj):
            fc = FileChooserIconView(title= 'upload image')
            image_path = self.fc.selection[0]
            image_name = file_path.split('/')[-1]

            with self.canvas.before:
                Rectangle(
                    size=self.size,
                    pos=self.pos,
                    source=image_name)
            Choose.bind(on_release=choose_file)


        return parent


if __name__ == '__main__':
    MyPaintApp().run()

这个怎么样:

如果您使用 kivy 文件选择器让用户select 一个图像文件, 那么您可以使用文件选择器的 .selection 属性来获取该文件的名称 and/or 路径。一旦你有了它,你就可以用它来在你想要背景图像的布局等 canvas 上设置矩形的来源。

例如,要在 BoxLayout 上设置背景图像,在继承自 BoxLayout 的 class 中:

fc = FileChooserIconView(title="Choose Image")
image_path = self.fc.selection[0]
image_name = file_path.split('/')[-1]

with self.canvas.before:
    Rectangle(
        size=self.size,
        pos=self.pos,
        source=image_name)

这当然是一个非常简单的示例,并没有真正考虑到您的其余代码,但是通过 FileChooser 上的 kivy 文档,您应该可以得到它。还值得注意的是,您可以在 kv 文件中执行此操作,也许更干净。