我对GUI设计非常陌生,并尝试使用python和kivy创建一个非常简单的应用程序,并在按下按钮后使用一些动画。但是,因为我对kivy完全陌生,所以我被困住了。我认为答案很简单,但经过8小时的试验和错误以及谷歌上网搜索后,我绝望了: - )
我创建了一个带按钮和图像的小应用程序。我尝试做的是在" button_pressed"之后更改图像。 kivy文件中的代码:
<FirstTest>:
my_image: my_image
source_image: self.source_image
Button:
on_press: root.gamer.changeImage()
My_Image:
id: my_image
source: self.parent.source_image
<My_Image>:
allow_stretch:True
keep_ratio: False
和python代码(只是必要部分):
class Player(object):
def changeImage(self):
FirstTest.source_image = 'new_image.png'
class My_Image(Image):
pass
class FirstTest(FloatLayout):
my_image = ObjectProperty(None)
source_image = StringProperty(None)
source_image = 'First_Image.png'
gamer = Player()
def update(self, dt):
print(self.source_image) #To see in realtime if the image source changed
class MyApp(App):
def build(self):
game = FirstTest()
Clock.schedule_interval(partial(FirstTest.update, FirstTest), 1/60)
return game
当我启动应用程序时,我看到了按钮和&#34; First_Image&#34;加载。但是当我按下按钮时没有任何变化。我唯一看到的是控制台中的source_image路径发生了变化。 我不明白为什么Image没有重新加载新的源代码。我想当我改变路径时我会得到一个新的图像,如果我重复这个,我会得到某种动画。但即使是单个图像也没有变化。如果我尝试更改&#34; my_image&#34;的对象属性我收到了一条错误消息&#34; ObjectProperty没有属性源&#34;
我想念什么?请帮忙!
提前致谢!
答案 0 :(得分:1)
我在您的代码中看到的最明显的问题是您将类对象与实例对象混淆。
FirstTest
是一个类对象,当你这样做时:
game = FirstTest()
您正在创建FirstTest
的实例。该实例将具有自己的属性和方法。这意味着您不想拨打FirstTest.update
,而是game.update
。
此外,FirstTest.source_image = ...
是错误的,因为您没有更改GUI中实例对象上的图像源,而是修改类定义。您需要修改game.source_image
。最简单的方法是在App对象中保存游戏引用(self.game = game
中的build
),然后使用App.get_running_app().game
引用它。