Advertisement
here2share

# tk_super_textbox_multiselect.py

Sep 8th, 2024
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. # tk_super_textbox_multiselect.py
  2.  
  3. import tkinter as tk
  4. from collections import deque
  5.  
  6. def do_toggle(i):
  7.     if i in toggle:
  8.         text.tag_remove("highlight", f"{i}.0", f"{i+1}.0")
  9.         toggle.remove(i)
  10.     else:
  11.         text.tag_add("highlight", f"{i}.0", f"{i+1}.0")
  12.         toggle.append(i)
  13.        
  14. def line_idx(event):
  15.     return int(text.index(f"@0, {event.y}").split(".")[0])
  16.  
  17. def on_drag(event):
  18.     i = line_idx(event)
  19.     if i != prev_2_lines[1]:
  20.         if i in prev_2_lines:
  21.             do_toggle(prev_2_lines[1])
  22.         do_toggle(i)
  23.         prev_2_lines.append(i)
  24.  
  25. def on_b1press(event):
  26.     i = line_idx(event)
  27.     do_toggle(i)
  28.     prev_2_lines.clear()
  29.     prev_2_lines.extend([-1, i])
  30.  
  31. root = tk.Tk()
  32.  
  33. items = [f"Item {i+1}" for i in range(30)]
  34.  
  35. toggle = []
  36. prev_2_lines = deque(maxlen=2)
  37. prev_2_lines.extend([-1, -1])
  38.  
  39. text = tk.Text(root, wrap=tk.NONE)
  40. text.bind("<B1-Motion>", on_drag)
  41. text.bind("<Button-1>", on_b1press)
  42.  
  43. for item in items:
  44.     text.insert(tk.END, item + "\n")
  45. text.delete(text.index("end-1c linestart"), tk.END)
  46.  
  47. scrollbar = tk.Scrollbar(root, orient="vertical", command=text.yview)
  48. text.configure(yscrollcommand=scrollbar.set)
  49.  
  50. text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
  51. scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
  52.  
  53. text.tag_configure("highlight", foreground="black", background="light green")
  54. text.tag_configure("sel", foreground="black", background="white")
  55.  
  56. root.mainloop()
  57.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement