问题
I want to make time counter with progressbar.The bar should be filled as time progresses.
I've progresed with the logic in the codes below, but the code starts before the program opens.
The bar should be stuffed every second.At least that's what I think.
'''
def update_time(self):
while self.ids.pb.value < 30:
time.sleep(1)
self.ids.pb.value+=1
'''
Related .kv file.
'''
<Question>:
name:"questions"
canvas.before:
Rectangle:
pos: self.pos
size: self.size
source: 'bg2.jpg'
FloatLayout:
Label:
id:quest
pos_hint: {"x":0.1,"y":0.62}
size_hint: 0.7,0.5
text:root.sendquest()
color:1, 0, 0, 1
ProgressBar:
id : pb
min :0
max :30
pos_hint: {'x': 0.1,"y":0.45}
size_hint_x :0.8
size_hint_y :0.03
background_color:0.8, 0.1, 0.1, 0
Button: #A
id:A
pos_hint: {"x":0.045,"y":0.376}
size_hint: 0.91,0.055
on_press:
root.reset() if root.check_truth("A") else root.popup()
'''
There are functions that are not relevant to this subject in main.py file.
回答1:
Kivy Programming Guide » Events and Properties
In Kivy applications, you have to avoid long/infinite loops or sleeping.
Solution
The solution is to use either Triggered Events (e.g. create_trigger() function) or Schedule Interval (e.g. schedule_interval() function).
Snippets - schedule_interval()
from kivy.properties import ObjectProperty
from kivy.clock import Clock
class RootWidget(ProgressBar):
tick = ObjectProperty(None)
def __init__(self, **kwargs):
super(RootWidget, self).__init__(**kwargs)
self.max = 30
self.tick = Clock.schedule_interval(lambda dt: self.update_time(), 1)
def update_time(self):
self.value += 1
if self.value >= 30:
self.tick.cancel() # cancel event
Snippets - create_trigger()
from kivy.properties import ObjectProperty
from kivy.clock import Clock
class RootWidget(ProgressBar):
tick = ObjectProperty(None)
def __init__(self, **kwargs):
super(RootWidget, self).__init__(**kwargs)
self.max = 30
self.tick = Clock.create_trigger(lambda dt: self.update_time(), 1)
self.tick()
def update_time(self):
self.value += 1
if self.value < 30:
self.tick()
else:
self.tick.cancel() # cancel event
来源:https://stackoverflow.com/questions/56990499/kivy-how-can-i-create-time-counter-with-progressbar