我正在尝试创建一个简单的应用程序,它会在单击按钮后显示图像。
到目前为止,我已设法在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()
答案 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)
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()