Skip to content Skip to sidebar Skip to footer

How To Insert A Python Script In A Class In Kivy?

I have a python text that I want to put in a class in kivy. Then I would like to use this class as a function and call it from another class. How should I define the class? What sh

Solution 1:

If you want to create a class put object in brackets --> class FaceGenerator(object): But in your case there is simply no need for a class, what you are looking for is a function. If I understand it correctly you only want to call one function on that class so you could just only define a function in the first place

Here is one way of doing what I think you would like to do:

from kivy.app import App
from kivy.base import Builder
from kivy.properties import ObjectProperty
from kivy.uix.boxlayout import BoxLayout


defFaceGenerator():
    #do your stuff
    face = 'PalimPalim'return face

Builder.load_string("""
<rootwi>:
    label_to_be_changed: label_to_be_changed
    orientation: 'vertical'
    Button:
        text:'klick me'
        on_press: root.change_Label_text()
    Label:
        id: label_to_be_changed

""")
classrootwi(BoxLayout):
    label_to_be_changed = ObjectProperty()

    defchange_Label_text(self):
        temp_str = FaceGenerator()
        self.label_to_be_changed.text = temp_str

classMyApp(App):
    defbuild(self):
        return rootwi()

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

some more Infos

  • root in the kv refers to the left most widget in this case rootwi
  • Defining an ObjectProperty for a widget which is part of a widget is my favorite way of doing any updating of properties. There are for sure other ways.

Solution 2:

@PalimPalim I worked as your structure above. My code is now like this Python code

import kivy
import cv2, os
import numpy as np
from PIL import Image

from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.button import Button
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.config import Config
Config.set('graphics', 'fullscreen', '0')
Config.set('graphics','show_cursor','1')

defFaceGenerator():
# open the camera and capture video
    cam = cv2.VideoCapture(0)
    face_detector = 
    cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    ID = 0
    sample_number = 0# a counter that counts the number of pictures for 
    each person in the database

    # detecting the face and draw rectangle on itwhile (True):
        retval,image = cam.read() # reading image from camprint np.shape(image)
        gray_image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # converting 
        image to gray image
        faces = face_detector.detectMultiScale(gray_image,1.3,5)
        ''' detectMultiScale, detects objects of different sizes in the 
        input image.
        the detected objects are returned as a list of rectangles
        '''for (x,y,w,h) in faces:
            cv2.rectangle(image, (x,y), (x+w, y+h), (255,0,0), 2)
            sample_number=sample_number+1# saving the captured face in the facebase folder

            cv2.imwrite('Trainer/User.'+str(ID)+'.'+str(sample_number)+'.jpg',
            gray_image[y:y+h,x:x+w])
    # this loop drawing a rectabgle on the face while the cam is open 
        cv2.imshow('frame',image)
        if cv2.waitKey(100) & 0xFF == ord('q'):
            breakelif sample_number==20:
            break

    cam.release()
    cv2.destroyAllWindows()
    output = "Succesfully created trainning set"return output

classScreenOne(Screen):
    passclassScreenTwo(Screen):
    passclassScreenThree(Screen):
        passclassScreenManagement(ScreenManager):
    pass


sm = Builder.load_file("facerecognition.kv")

classFaceRecognitionApp(App):
    defbuild(self):
        return sm

if __name__=="__main__":
    FaceRecognitionApp().run()

The .KV file is:

ScreenManagement:id:screen_managementScreenOne:ScreenTwo:ScreenThree:<ScreenOne>:name:"screen1"id:screen_oneFloatLayout:canvas.before:Rectangle:source:"image1.jpg"pos:self.possize:self.sizeLabel:text:"Hello\nWelcometomyApp\n"font_size:40color:0,0,0,1Button:text:'Next'font_size:32# font sizesize_hint:.2,.1pos_hint:{'right':1,'y':0}on_release:app.root.current="screen2"<ScreenTwo>:name:"screen2"id:screen_twoFloatLayout:canvas:Rectangle:source:"image1.jpg"pos:self.possize:self.sizeLabel:text:"PleaseinsertyourName\nPleaseinsertyourPassword\n"font_size:40color:0,0,0,1Button:text:'Next'font_size:32# font sizesize_hint:.2,.1pos_hint:{'right':1,'y':0}on_release:app.root.current="screen3"<ScreenThree>:name:"screen3"id:screen_threeFloatLayout:canvas:Rectangle:source:"image1.jpg"pos:self.possize:self.sizeButton:text:'Next'font_size:32# font sizesize_hint:.2,.1pos_hint:{'right':1,'y':0}on_release:app.root.current="screen1"BoxLayout:orientation:'horizontal'FaceGenerator()

Post a Comment for "How To Insert A Python Script In A Class In Kivy?"