I try to display a random image in the GUI Kivy window from python code

Viewed 20

I try to display random images in the kivy window but with no success and i am stuck here now.. I followed a tutorial for this in KV code but i need to do that in py so if someone can show me where I am wrong please . THANKS !!

from kivy.app import App
from kivy.uix import image
from kivy.uix.floatlayout import FloatLayout
from PIL import Image
import random


class MyRoot(FloatLayout):

    def __init__(self):
        super(MyRoot, self).__init__()

    image = Image.open("Q1.png")
    image.show()


    def generate_question(self):
        choices = (image)
        self.random_question.image = random.choice(choices)


class RandomQuestionApp(App):
    def build(self):
        return MyRoot()


randomApp = RandomQuestionApp()
RandomQuestionApp().run()

<MyRoot>:
    random_question: random_question
    FloatLayout:
        orientation: "vertical"

        Label:
            id: random_question
            text: " "
            font_size: self.width/30

        Button:
            text: "Ask"
            font_size: self.width/8
            on_press: root.generate_question()
            pos_hint:{"x":0.38,"y":0.35}
            size_hint: 0.18, 0.075

1 Answers
from kivy.app import App
from kivy.uix.image import Image
from kivy.uix.button import Button


from random import choice

class MyImage(Image):
    images = ['1.png','2.png','3.png'] #........
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        self.add_widget(
                Button(
                    on_release=self.random_image
                    )
            )
        self.random_image()
    def random_image(self ,*_):
        self.source = choice(self.images)
    


class RandomQuestionApp(App):
    def build(self):
    
        return MyImage()


randomApp = RandomQuestionApp()
RandomQuestionApp().run()
Related