I have a Treeview in which I change the headings based on whether the element below the mouse is a top level element or not. For this I use the <Motion> event:
What I noticed is, unless I use the after function to schedule the motion callback, it leads to CPU spikes. I also use a deque to make sure that at most, the callback is scheduled for once only. This means that if the deque will be popped and if it has an element, then only it will be cancelled and rescheduled again.
EDIT: I noticed that this happens only for a table where the number of items is significant (5000+)
import collections
import tkinter as tk
from tkinter import ttk
class Tv(tk.Tk):
def __init__(self):
super().__init__()
self.tv = ttk.Treeview()
self.tv.bind("<Motion>", lambda *_: self.manage_headings())
self.tv.pack()
self._after_dq = collections.deque(1)
def manage_headings():
def after_func():
if self.tv.parent(iid):
pass
else:
pass
try:
prev_id = self._after_dq.popleft()
except IndexError:
self._after_dq.append(self.after(10, after_func))
else:
self.after_cancel(prev_id)
However I notice, the CPU usage doesn't really go down than from just using after directly and not even bothering to cancel it later.