completer点击选择改为双击选择,代码实现
时间: 2023-07-16 09:11:38 浏览: 59
选择算法实现代码
可以通过更改 `Completer` 类的 `_listbox` 方法来实现将点击选择改为双击选择。具体实现代码如下:
``` python
import tkinter as tk
from tkinter import ttk
class DoubleClickCompleter(ttk.Entry):
def __init__(self, master, options=[], **kwargs):
super().__init__(master, **kwargs)
self.options = sorted(options, key=str.lower) if options else []
self.current_options = []
self._listbox = None
self._listbox_visible = False
self._selected_index = None
self.bind("<KeyRelease>", self._on_key_release)
self.bind("<Return>", self._on_return)
self.bind("<Button-1>", self._on_click)
self.bind("<Double-Button-1>", self._on_double_click)
def _on_key_release(self, event):
"""
Event handler for key releases. Updates the listbox with the current options.
"""
self.current_options = [
option for option in self.options if self.get().lower() in option.lower()
]
self._update_listbox()
def _on_return(self, event):
"""
Event handler for the return key. Inserts the selected option into the entry widget.
"""
if self._listbox_visible:
self.delete(0, tk.END)
self.insert(0, self._listbox.get(tk.ACTIVE))
self._listbox_visible = False
self._listbox.destroy()
self.icursor(tk.END)
def _on_click(self, event):
"""
Event handler for mouse clicks. Hides the listbox if it is visible.
"""
if self._listbox_visible:
self._listbox_visible = False
self._listbox.destroy()
def _on_double_click(self, event):
"""
Event handler for double mouse clicks. Inserts the selected option into the entry widget.
"""
if self._listbox_visible:
self.delete(0, tk.END)
self.insert(0, self._listbox.get(tk.ACTIVE))
self._listbox_visible = False
self._listbox.destroy()
self.icursor(tk.END)
def _update_listbox(self):
"""
Updates the listbox with the current options.
"""
if not self.current_options:
if self._listbox_visible:
self._listbox_visible = False
self._listbox.destroy()
else:
if not self._listbox_visible:
self._listbox = tk.Listbox(
master=self.master,
height=len(self.current_options),
exportselection=False,
)
self._listbox.bind("<Button-1>", self._on_click)
self._listbox.place(
x=self.winfo_x(),
y=self.winfo_y() + self.winfo_height(),
)
self._listbox_visible = True
self._listbox.delete(0, tk.END)
for option in self.current_options:
self._listbox.insert(tk.END, option)
```
在这个实现中,我们新增了一个 `_on_double_click` 方法,用于处理双击事件。同时在 `_on_click` 中也需要加入判断,避免在双击时出现不必要的操作。
阅读全文