Advertisement
here2share

# tk_power_listbox.py

Jun 3rd, 2024
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. # tk_power_listbox.py
  2.  
  3. from tkinter import *
  4.  
  5. root = Tk()
  6. root.title("tk_power_listbox")
  7. menu_options = list(range(300))
  8. frame = Frame(root)
  9. frame.pack()
  10. label = Label(frame, text="Hello Tkinter")
  11. label.pack(side=LEFT)
  12. text_box = Text(frame, height=1, bg='yellow')
  13. text_box.pack(side=LEFT, padx=3, pady=3)
  14.  
  15. def on_active(event):
  16.     global selected_index
  17.     listbox2.itemconfig(selected_index, bg='white')
  18.     selected_index = listbox2.nearest(event.y)
  19.     listbox2.itemconfig(selected_index, bg='yellow')
  20.  
  21. def on_select(event):
  22.     selection = listbox2.curselection()[0]
  23.     text_box.delete('1.0', END)  # Clear the previous text
  24.     text_box.insert(END, str(menu_options[selection]))  # Insert the new text
  25.     root2.destroy()
  26.  
  27. screen_h = root.winfo_screenheight()
  28.  
  29. def on_enter(event):
  30.     global root2, listbox2, selected_index
  31.     try:
  32.         root2.destroy()
  33.     except:
  34.         pass
  35.     selected_index = 0
  36.     root2 = Toplevel()
  37.     root2.overrideredirect(True)
  38.     Lmenu = min(30, len(menu_options))
  39.     Lb2 = Lmenu * 14
  40.     listbox2 = Listbox(root2, height=Lmenu)
  41.     yyy = root.winfo_y() + 20
  42.     if yyy + Lb2 > screen_h:
  43.         yyy = screen_h - Lb2
  44.     root2.geometry("+{}+{}".format(text_box.winfo_x() + root.winfo_x() + 8, yyy))
  45.     for option in menu_options:
  46.         listbox2.insert(END, option)
  47.     scrollbar = Scrollbar(root2, orient=VERTICAL, command=listbox2.yview)
  48.     scrollbar.pack(side=RIGHT, fill=Y)
  49.     scrollbar.config(width=40)
  50.     listbox2.config(yscrollcommand=scrollbar.set)
  51.     root2.bind("<Motion>", on_active)
  52.     root2.bind("<Leave>", on_leave)
  53.     listbox2.bind("<<ListboxSelect>>", on_select)
  54.     listbox2.pack()
  55.  
  56. def on_leave(event):
  57.     x = root.winfo_pointerx()
  58.     geom = root2.geometry()
  59.     x2y2, w, h = geom.split("+")
  60.     x2, y2, w, h = [int(i) for i in x2y2.split("x") + [w, h]]
  61.     if (x < x2 + w - 50 or x > x2 + w):
  62.         root2.destroy()
  63.     # destroys if outside of top or bottom automaticallY? nice
  64.  
  65. text_box.bind("<Button-1>", on_enter)  # Bind on_enter to left mouse click
  66. root.mainloop()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement