0

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,

3
  • You want to clear all data inside the TreeView before your View() method adds data to it. See this answer. Commented Jan 30, 2021 at 17:08
  • Every time I click the button it duplicates the data, I want it to fetch new data after clearing the existing ones. Commented Jan 30, 2021 at 17:33
  • Have you tried deleting the old entries before inserting the new? Commented Jan 30, 2021 at 17:39

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.