我正在嘗試創建一個按鈕,當按下它時,它會在 1-10 范圍內連續顯示一個隨機整數,持續 10 秒。我對 kivy 完全陌生,但我已經在互聯網上搜索了相關問題,所以請溫柔一點。
目前標簽文本只顯示最后一個數字。Kivy 等待 for 回圈完成并顯示生成的最終數字。當 for 回圈發生時,kivy gui 將消失。任何形式的幫助將不勝感激!
以下是我的代碼和kv檔案。
class WidgetExample(GridLayout):
my_text = StringProperty('Press Click me')
def on_button_click(self):
for i in range(1,10):
i=random.randint(1,10)
time.sleep(1)
print(i)
self.my_text = str(i)
class TheLabApp(App):
pass
TheLabApp().run()
WidgetExample:
<WidgetExample>:
cols: 3
Button:
text: 'Click me'
on_press: root.on_button_click()
Label:
text: root.my_text
uj5u.com熱心網友回復:
當 for 回圈發生時,kivy gui 將消失......
顯然這不是真的。您的回呼do_button_click在與 GUI 相同的執行緒上運行,但按順序運行。這就是為什么一旦回呼的執行完成,它就會在 GUI 中呈現最終結果。要單獨執行,您可以使用另一個執行緒而不影響主執行緒。
def on_button_click(self):
# Start a new thread. Be aware of creating new thread every time you press the button.
# In which case you need to keep a reference or track the created thread.
threading.Thread(target = self.do_button_click).start()
def do_button_click(self):
for i in range(1,10):
i=random.randint(1,10)
time.sleep(1)
print(i)
self.my_text = str(i)
或者,您可以使用模塊Clock。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/530052.html
標籤:Pythonpython-3.x用户界面基维kivy 语言
上一篇:你將如何在反應中實作這一點?
