【问题标题】:Display image from different funtion in kivy python在kivy python中显示来自不同功能的图像
【发布时间】:2020-07-18 05:44:17
【问题描述】:

您好,我正在尝试构建一个扫描仪,它可以拍摄图像并单击提交按钮,它应该在新屏幕中返回结果图像,这是我到现在为止的地方,非常感谢您的帮助。提前致谢

from kivy.app import App
from kivy.lang import Builder
import time
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.image import Image

Builder.load_string( '''
<CameraClick>:
orientation: 'vertical'
Camera:
    id: camera
    resolution: 500,500
BoxLayout:
    orientation: 'horizontal'
    size_hint_y: None
    height: '48dp'
    Button:
        text: 'Click'
        on_press: root.capture()
        on_release: camera.play = False
    Button:
        text: 'Submit'
        on_press: root.capture()
        on_release: camera.play = False
''')

class CameraClick(BoxLayout):
def capture(self):
    '''
    Function to capture the images and give them the names
    according to their captured time and date.
    '''
    camera = self.ids['camera']
    print("camera down")
    print(type(camera))
    timestr = time.strftime("%Y%m%d_%H%M%S")
    camera.export_to_png("IMG_{}.png".format(timestr))
    print("Captured")
    return Image(source='hey.png')

#  def release(self):
    

class CameraApp(App):
    def build(self):
        return CameraClick()


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

【问题讨论】:

  • 分配给按钮(或菜单)的函数无法返回值,因为没有对象可以获取此值。您应该将其分配给全局变量或类变量 - 即。 self.image - 和其他类/函数应该从这个变量中获取它。

标签: python opencv kivy kivy-language


【解决方案1】:

当您单击按钮时,Kivy 运行分配的函数但它没有得到返回值 - 它不知道如何处理返回值。

您必须为全局变量或类(使用self.)赋值,其他函数必须从该变量中获取值。

def capture(self):
    self.image = Image(source='hey.png')

def other_function(self):
    do_something(self.image)

如果other_function 可以在capture 之前执行,那么最好在开始时使用一些默认值创建这个变量 - 即。 None

class CameraClick(BoxLayout):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.image = None

然后你可以检查capture是否被执行

def other_function(self):

    if self.image:
        do_something(self.image)
    else:
        print('Image not captured yet')

如果您想在不同的类中使用该值,那么您可能必须将其分配给全局变量 - 最终,如果可能的话,您可以将一个类的实例作为参数发送给另一个类

camera_click =  CameraClick()
OtherClass(camera_click)

其他类可以保留它,以后可以使用它来获取图像

class OtherClass():

    def __init__(self, camera, **kwargs):
        super().__init__(**kwargs)

        self.camera = camera


    def some_function(self):
       
        if self.camera.image:
            do_something(self.camera.image)
        else:
            print('Image not captured yet')

顺便说一句:有时类可能有相同的parent,然后OtherClass 可以使用

 self.parent.camera_click.image

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-07
    • 2013-05-19
    • 1970-01-01
    • 2012-01-27
    相关资源
    最近更新 更多