Tkinter Drag and drop the items in the Listbox
Another important application in the process of creating a Listbox is the ability to drag and drop options, and the following will explain this aspect of the application with examples.
Example#1
Create the Listbox first, and then you can drag and drop the selected items.
from tkinter import *
def getIndex(event): # Handling Click Options
lb.index = lb.nearest(event.y) # Index of current options
cnt = 0
def dragJob(event):
newIndex = lb.nearest(event.y)
global cnt
cnt += 1
print("**********************",cnt)
if newIndex < lb.index:
x = lb.get(newIndex)
lb.delete(newIndex)
lb.insert(newIndex+1,x)
lb.index = newIndex
print("Upward adjustment successfully...")
elif newIndex > lb.index:
x = lb.get(newIndex)
lb.delete(newIndex)
lb.insert(newIndex-1,x)
lb.index = newIndex
print("Downward adjustment successfully...")
fruits = [
"Banana","Watermelon","Pineapple",
"Orange","Grapes","Mango"
]
root = Tk()
root.title("apidemos.com")
# root.geometry("300x250")
lb = Listbox(root) # Create Listbox
for fruit in fruits:
lb.insert(END,fruit)
lb.bind("<Button-1>",getIndex)
lb.bind("<B1-Motion>",dragJob)
lb.pack(padx=10,pady=10)
root.mainloop()
Output:
The following methods are used in this program on lines 3 and 6.
nearest(event.y)
The above lines of code pass back the index of the closest y coordinate in the Listbox. The getIndex( ) method is triggered when there is a click operation, and the index of the current option can be passed back in line 4. The dragJob( ) method is triggered during the dragging process, and the index of the new option is passed back in line 7.
If the above example, the current index of the option Watermelon is 1, the process of dragging is as follows. Referring to the execution process of the code of example 1, is to move down, the entire process is described below.
(1) the new index position is 2.
(2) to obtain the content of index 2 Pineapple, refer to line 13.
(3) Delete the content of index 2 Pineapple, which can be referred to line 14.
(4) Insert the content of Pineapple, which is equivalent to inserting the index 1 position, refer to line 16.
(5) At this time, the index of the current option Watermelon becomes 2, so as to achieve the purpose of moving the option, refer to line 16.