Kivy没有显示图片

时间:2018-04-26 10:06:51

标签: python kivy

我正在尝试创建一个简单的应用程序,它会在单击按钮后显示图像。

到目前为止,我已设法在ShootButton类中创建按钮并将其绑定到Bullet类。问题是在调用'Bullet'类后,图像不会出现。我知道该类被调用,因为它打印“test”,但没有图像。

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.image import Image
from kivy.uix.widget import Widget


Window.size = (360, 640)

class Game(Widget):
    pass


class ShootButton(Widget):
    def shoot(self):
        shooting = Bullet()
        shooting.bullet_fly()

class Bullet(Widget):
    def bullet_fly(self):
        img = Image(source='bullet.png')
        self.add_widget(img)
        print('test')

class MyApp(App):
    def build(self):
        return Game()

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

和Kv文件:

<Game>
    ShootButton:


<ShootButton>
    Button:
        text: "shoot!"
        size: 70,50
        font_size: 20
        pos: 100,100
        on_press: root.shoot()

2 个答案:

答案 0 :(得分:2)

您没有将项目符号小部件添加到kivy层次结构中。

我相信你会想做这样的事情:

class ShootButton(Widget):
    def shoot(self):
        shooting = Bullet()
        self.parent.add_widget(shooting.img)
        shooting.bullet_fly()

答案 1 :(得分:1)

要将项目符号图像添加到根目录(游戏),请使用 App.get_running_app()。root.add_widget(img)

片段

class Bullet(Widget):
    def bullet_fly(self):
        img = Image(source='bullet.png', size_hint_y=None, height=dp(40), pos=(85, 200))
        App.get_running_app().root.add_widget(img)

实施例

main.py

from kivy.app import App
from kivy.core.window import Window
from kivy.uix.image import Image
from kivy.uix.widget import Widget
from kivy.metrics import dp


Window.size = (360, 640)


class Game(Widget):
    pass


class ShootButton(Widget):
    def shoot(self):
        shooting = Bullet()
        shooting.bullet_fly()


class Bullet(Widget):
    def bullet_fly(self):
        img = Image(source='bullet.jpeg', size_hint_y=None, height=dp(40), pos=(85, 200))
        App.get_running_app().root.add_widget(img)
        print('test')


class MyApp(App):
    def build(self):
        return Game()


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

输出

Img01 - App Startup Img02 - Bullet flying