使用 tkinter 按钮从 MySQL 获取数据被复制 [英] Getting data from MySQL using tkinter button gets duplicated

查看:28
本文介绍了使用 tkinter 按钮从 MySQL 获取数据被复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 python 脚本,它使用 tkinter 和一个按钮从 MySQL 获取数据,但是每次我按下按钮时,数据都会像这样重复:

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:

以下代码:

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?

问候,

推荐答案

你可以做一个简单的检查,如果里面有项目就删除所有项目,如果没有则插入,比如:

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.

这篇关于使用 tkinter 按钮从 MySQL 获取数据被复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆