How To Move Tkinter Treeview Selected Rows Up N Down In Python
In this Python Tkinter Tutorial we will see How To Get Treeview Selected Row And Move This Row Up & Down By Changing The position Using The move Function On Two Buttons Click Event In Python Programming language And Tkinter GUI .
Source Code:
import tkinter as tk
from tkinter import *
from tkinter import ttk
root = Tk()
root.title("Move Row UP and DOWN")
frame_container = tk.Frame(root, padx=10, pady=10, bg='#badc58')
frame_fields = tk.Frame(frame_container, bg='#badc58')
# create treeview
trv = ttk.Treeview(frame_container, columns=(1,2,3,4), show='headings')
trv.column(1, anchor='center', width=100)
trv.column(2, anchor='center', width=100)
trv.column(3, anchor='center', width=100)
trv.column(4, anchor='center', width=100)
trv.heading(1, text='ID')
trv.heading(2, text='Name')
trv.heading(3, text='Quantity')
trv.heading(4, text='Price')
# add items to the treeview
trv.insert("",'end', iid=1, values=(1,"Product 1",100, 10))
trv.insert("",'end', iid=2, values=(2,"Product 2",200, 20))
trv.insert("",'end', iid=3, values=(3,"Product 3",300, 30))
trv.insert("",'end', iid=4, values=(4,"Product 4",400, 400))
trv.insert("",'end', iid=5, values=(5,"Product 5",500, 50))
trv.insert("",'end', iid=6, values=(6,"Product 6",600, 60))
# create a function to move the selected row up
def moveUp():
leaves = trv.selection()
for i in leaves:
trv.move(i, trv.parent(i), trv.index(i)-1)
# create a function to move the selected row down
def moveDown():
leaves = trv.selection()
for i in reversed(leaves):
trv.move(i, trv.parent(i), trv.index(i)+1)
btn_up = tk.Button(frame_fields, text='UP', command=moveUp)
btn_down = tk.Button(frame_fields, text='DOWN', command=moveDown)
btn_up.grid(row=0, column=0, padx=10, pady=10, sticky='e')
btn_down.grid(row=0, column=1)
trv.pack()
frame_container.pack()
frame_fields.pack()
root.mainloop()
OUTPUT:
Python Move Selected Tkinter Treeview Row Up |
Python Move Selected Tkinter Treeview Row Down |