Reputation: 13
Let's consider the following piece of code:
#.py file
class Screen:
def change_text():
self.ids.btn.text="some text"
#.kv file
<Screen>:
GridLayout:
cols:1
Button:
id:btn
on_press: root.change_text()
As soon as the button is pressed, its text will be changed. But how can I change the code so that the text is changed only when the button is continuously pressed for let's say 3 seconds?
Upvotes: 0
Views: 53
Reputation: 38857
If you want to change the text only after holding the Button down for 3 seconds, you can do something like this:
kv:
<Screen>:
GridLayout:
cols:1
Button:
id:btn
on_press: root.start_timer()
on_release: root.cancel_timer()
py:
class Screen(FloatLayout):
def __init__(self, **kwargs):
super(Screen, self).__init__(**kwargs)
self.timer = None
def start_timer(self):
if self.timer:
self.timer.cancel()
self.timer = Clock.schedule_once(self.change_text, 3.0)
def cancel_timer(self):
if self.timer:
self.timer.cancel()
def change_text(self, dt):
self.ids.btn.text="some text"
This uses Clock.schedule_once()
to schedule the text change for 3 seconds later. Both the on_press
and on_release
cancel any current timer (although it is probably not necessary for the on_press
.
Upvotes: 1
Reputation: 38857
You can just build some logic in the Screen
class:
class Screen(FloatLayout):
def __init__(self, **kwargs):
super(Screen, self).__init__(**kwargs)
self.start_time = 0
self.count = 0
def change_text(self):
time_now = time.time()
if time_now - self.start_time > 3.0:
# longer than 3 seconds since first click, start over
self.start_time = time_now
self.count = 1
else:
# this click within 3 seconds
self.count += 1
if self.count == 3:
# 3 clicks within 3 seconds, so make the text change
self.ids.btn.text="some text"
self.count = 0
self.start_time = 0
Upvotes: 0