我需要拥有随机屏幕数的Kivy屏幕管理器,每个屏幕都有一些图像。我试图逐个显示每个屏幕有一些延迟。 我能够部分实现它。当我运行我的应用程序时它只显示第一个屏幕,下一个按钮我移动到下一个屏幕(图像),然后继续显示屏幕,直到它到达最后一个。
代码如下所示:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.properties import NumericProperty
from kivy.lang import Builder
import time
Builder.load_string('''
#:import random random.random
#:import NoTransition kivy.uix.screenmanager.NoTransition
<CustomScreen>:
Image:
source: root.name
Button:
text: 'Next screen'
size_hint: None, None
pos_hint: {'right': 1}
size: 150, 50
on_release: root.callbackfun()
''')
class CustomScreen(Screen):
def on_enter(self,*args):
time.sleep(0.5)
print "on Enter"
if self.manager.current != "image10.jpg":
self.callbackfun()
def callbackfun(self):
print "Change Screen"
print self.manager.current
print self.manager.next()
self.manager.current = self.manager.next()
class ScreenManagerApp(App):
def build(self):
root = ScreenManager(transition = NoTransition(duration = 0))
for x in range(11):
print "add", x
root.add_widget(CustomScreen(name='image%d.jpg' % x))
return root
if __name__ == '__main__':
ScreenManagerApp().run()
首先 print self.manager.current
和 print self.manager.next()
都显示0
,但按下按钮后,它会显示当前和下一个屏幕正确。
答案 0 :(得分:0)
在Kivy应用程序中使用 time.sleep 。
Programming Guide » Events and Properties » Main Loop
在Kivy应用程序中,您必须避免长/无限循环或 睡觉,例如 time.sleep()这阻止了Kivy完成所有其他需要做的事情。
你可以使用 Clock.schedule_interval()或者使用 Clock.schedule_once()每秒调用一次函数或方法,你可以调用一个函数“稍后”,如下一帧,或X秒。
用 Clock.schedule_once()替换 time.sleep(0.5)。有关详细信息,请参阅以下示例。
class CustomScreen(Screen):
def on_enter(self, *args):
if self.manager.current != "image5.png":
Clock.schedule_once(self.callbackfun, 0.5)
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, NoTransition
from kivy.lang import Builder
from kivy.clock import Clock
Builder.load_string('''
#:import Clock kivy.clock.Clock
<CustomScreen>:
Image:
source: root.name
Button:
text: 'Next screen'
size_hint: None, None
pos_hint: {'right': 1}
size: 150, 50
on_release:
Clock.schedule_once(root.callbackfun, 0.5)
''')
class CustomScreen(Screen):
def on_enter(self, *args):
print("on Enter")
if self.manager.current != "image5.png":
Clock.schedule_once(self.callbackfun, 0.5)
def callbackfun(self, dt):
print("Change Screen")
print(self.manager.current)
print(self.manager.next())
self.manager.current = self.manager.next()
class ScreenManagerApp(App):
def build(self):
root = ScreenManager(transition = NoTransition(duration = 0))
for x in range(6):
print("add", x)
root.add_widget(CustomScreen(name='image%d.png' % x))
return root
if __name__ == '__main__':
ScreenManagerApp().run()