我正在嘗試使用 KIVY 和 gTTS 制作兒童學習應用程式,其中將向孩子展示隨機影像,并且必須通過說出它是什么來識別它(“正方形”表示正方形,“三”表示 3 等)。
到目前為止,我的選單作業正常。我random.choice()在字典中使用,其中值是影像路徑,鍵是“名稱”
如果我打開相關螢屏,則隨機正確選擇影像并使用顯示,def on_pre_enter(self, *args):并且 gTTS 也可以正常使用def on_enter(self, *args): ,但僅使用一次
我希望它在用戶回復前一個影像進行 X 次回圈后加載一個新的隨機影像,但無論我嘗試什么,我都無法讓它作業(我想把所有東西都放在一個 for x in range()回圈上以及使用計數器上一個while X < Y:但沒有任何成功)。
這是我的 .py 檔案
import random
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import StringProperty
class MenuWindow(Screen):
pass
class ShapeGame(Screen):
rand_shape = StringProperty()
def on_pre_enter(self, *args):
random_shape = {"square":'shapes/square.png', "triangle":'shapes/triangle.jpg', "circle":'shapes/circle.jpg'}
random_shape_key, random_shape_value = random.choice(list(random_shape.items()))
print(random_shape_key)
self.rand_shape_key = random_shape_key
self.rand_shape = random_shape_value
def on_enter(self, *args):
print(self.random_shape_key)
class WindowManager(ScreenManager):
pass
class MainApp(App):
def build(self):
return Builder.load_file('Main.kv')
if __name__ == '__main__':
MainApp().run()
和我的 .kv 檔案
#:kivy 2.0
WindowManager:
MenuWindow:
ShapeGame:
<MenuWindow>:
name: "menu"
BoxLayout:
orientation: "vertical"
size: root.width, root.height
Label:
id:"menu"
text: "Menu Screen"
font_size: 34
BoxLayout:
size_hint: 1.0, 0.2
Button:
text: "Shape Game"
font_size: 22
on_release:
app.root.current = "shapes"
root.manager.transition.direction = "left"
Button:
text: "Exit"
font_size: 22
size_hint: 1.0, 0.2
on_release: app.root.current = exit()
<ShapeGame>:
name: "shapes"
id: ShapeGame
BoxLayout:
orientation: "vertical"
size: root.width, root.height
Image:
id:"shapes"
screen: ShapeGame
source: self.screen.rand_shape
before_source: self.source
BoxLayout:
size_hint: 1.0, 0.2
size: root.width, root.height
Button:
text: "Menu"
on_release:
app.root.current = "menu"
root.manager.transition.direction = "right"
Button:
text: "Exit"
on_release:
app.root.current = exit()
和整個回購
uj5u.com熱心網友回復:
不確定我是否可以關注您的問題,假設您想在一段時間后在進入螢屏時隨機播放影像,直到某個值達到其限制。
為此,您可以使用Clock.schedule_interval一些等待時間,例如 2.0 秒。
因此,您的ShapeGame遺囑現在看起來像,
class ShapeGame(Screen):
rand_shape = StringProperty()
count = 0
def on_pre_enter(self, *args):
self.count = 0
self.change_event = Clock.schedule_interval(self.chage_photo, 2.0)
def chage_photo(self, *args):
if self.count < 3:
self.count = 1
else:
self.change_event.cancel()
random_shape = {"square":'shapes/square.png', "triangle":'shapes/triangle.jpg', "circle":'shapes/circle.jpg'}
random_shape_key, random_shape_value = random.choice(list(random_shape.items()))
print(random_shape_key)
self.rand_shape_key = random_shape_key
self.rand_shape = random_shape_value
您應該更改source: self.screen.rand_shape為source: root.rand_shape.
您也可以通過按鈕觸發相同的操作,而不是使用Clock.schedule.
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/444682.html
標籤:Python python-3.x 循环 字典 基维
