如何在连续按下按钮3秒时更改按钮的文本
How to change the text of a button when it is being continuosly pressed for 3 seconds
让我们考虑以下代码:
#.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()
只要按下按钮,它的文本就会改变。但是我怎样才能更改代码,以便仅当连续按下按钮 3 秒时才更改文本?
您可以在 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
如果你只想在按住按钮 3 秒后更改文本,你可以这样做:
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"
这使用 Clock.schedule_once()
将文本更改安排在 3 秒后。 on_press
和 on_release
都取消任何当前计时器(尽管 on_press
.
可能没有必要
让我们考虑以下代码:
#.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()
只要按下按钮,它的文本就会改变。但是我怎样才能更改代码,以便仅当连续按下按钮 3 秒时才更改文本?
您可以在 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
如果你只想在按住按钮 3 秒后更改文本,你可以这样做:
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"
这使用 Clock.schedule_once()
将文本更改安排在 3 秒后。 on_press
和 on_release
都取消任何当前计时器(尽管 on_press
.