Search code examples
pythontkintertreeview

Getting data from MySQL using tkinter button gets duplicated


I've a python script that uses tkinter and a button to get data from MySQL but every time I press the button the data gets duplicated like that: Tkinter

Code below:

from tkinter import ttk
import tkinter as tk
import mysql.connector

def View():
    mydb = mysql.connector.connect(
    host="localhost",
    user="",
    password="",
    database=""
    )
    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM patients")
    rows = mycursor.fetchall()
    for row in rows:
        print(row) 
        tree.insert("", tk.END, values=row)
    mydb.close()

# connect to the database
root = tk.Tk()
root.geometry("900x350")
tree = ttk.Treeview(root, column=("c1", "c2", "c3"), show='headings')
tree.column("#1", anchor=tk.CENTER)
tree.heading("#1", text="ID")
tree.column("#2", anchor=tk.CENTER)
tree.heading("#2", text="First Name")
tree.column("#3", anchor=tk.CENTER)
tree.heading("#3", text="Country")

tree.pack()
button1 = tk.Button(text="Display data", command=View)
button1.pack()
root.mainloop()

How can I make it print/get the data after clearing the last fetched data?

Regards,


Solution

  • You can do a simple check, if there are items inside and then delete all the items, and if not insert, like:

    def View():
        if len(tree.get_children()): # If there are items inside 
            tree.delete(*tree.get_children()) # Delete all the items
        else:
            # Paste the rest of code
    

    You can also define a flag and then check if data is inserted, and proceed accordingly, like:

    inserted = False # Initially False
    def View():
        if inserted:
            tree.delete(*tree.get_children())
            inserted = False # Set it to not inserted 
        if not inserted: # Let this get triggered
            # Same code
            for row in rows:
                print(row) 
                tree.insert("", tk.END, values=row)
            mydb.close()
            inserted = True # Set it to true.