Kivy:如何实现Label双击触发函数?替代on_ref_press方案咨询
实现Kivy Label中Ref文本的双击触发
Got it, so you want to trigger your function only when the labeled reference is double-clicked, instead of the default single-click from on_ref_press? Let's fix this—Kivy doesn't have a built-in double-click ref event, but we can build it with a custom Label subclass.
Step 1: Create a Custom Double-Click Ref Label
We'll subclass Label (or your existing MyLabel) to track click timings and check for double taps on ref text:
from kivy.uix.label import Label from kivy.clock import Clock from functools import partial class DoubleClickRefLabel(Label): def __init__(self, **kwargs): super().__init__(**kwargs) self.last_touch_time = 0 self.last_ref = None # Adjust this threshold (in seconds) to fit your needs self.double_click_threshold = 0.3 def on_touch_down(self, touch): if self.collide_point(*touch.pos): # Get the ref at the touched position ref = self.get_ref_at_pos(touch.pos) if ref: current_time = Clock.get_time() # Check if this is a double-click on the same ref if (current_time - self.last_touch_time) <= self.double_click_threshold and self.last_ref == ref: # Trigger the double-click event if hasattr(self, 'on_ref_double_press'): self.on_ref_double_press(ref) # Reset to prevent multiple triggers self.last_touch_time = 0 self.last_ref = None else: # Store first click data self.last_touch_time = current_time self.last_ref = ref return True # Pass other touches to the parent implementation return super().on_touch_down(touch)
Step 2: Replace Your Existing Label with the Custom One
Swap out MyLabel for DoubleClickRefLabel (if MyLabel has custom logic, make DoubleClickRefLabel inherit from MyLabel instead of Label), and bind your function to the new on_ref_double_press event:
layout.add_widget( DoubleClickRefLabel( text='[ref=world]' + str('Test') + '[/ref]', padding_x=10, size_hint_x=.35, halign='left', markup=True, on_ref_double_press=partial(self.xyz, 10) ) )
Key Details to Note
get_ref_at_pos(touch.pos): This Kivy Label method lets us check if the touch is on a marked ref text, so we don't trigger the function for clicks outside the ref.- Double-Click Threshold: The
0.3second value is a standard default, but you can tweakdouble_click_thresholdto make the double-click detection more or less sensitive. - Inheriting from Your Custom Label: If
MyLabelhas its own overrides (like custom styling or touch handling), change the class definition toclass DoubleClickRefLabel(MyLabel):to preserve that functionality.
内容的提问来源于stack exchange,提问作者macson taylor
相关产品推荐
相关产品推荐

