![](/img/trans.png)
[英]Why am I receiving a error when trying to use tkinter to make multiple windows gui?
[英]I am trying to make a GUI application using tkinter
I want to make two main function first import from Excel file(.xlsx) to my application and save the imported data to mysql database, second function is to export the file to excel file (.xlsx) after doing some other things to every record
我的主要問題是:
這是我的代碼:
'''
#import all what I need:
import tkinter as tk
from tkinter import *
from tkinter import ttk
from tkinter import messagebox, filedialog
import mysql.connector as mysql
import csv
import os
import pandas as pd
# define mydatabase:
db = mysql.connect( host = "localhost", user = "root", passwd = "S@mY2829", database="sample", auth_plugin="mysql_native_password")
cursor = db.cursor()
#Global variable:
mydata = []
root = Tk()
#define my fuctions:
#1
def update(records):
global mydata
mydata = records
trv.delete(*trv.get_children())
for i in records:
trv.insert('', 'end', values=i)
#2
def clear():
query = "SELECT * FROM demo"
cursor.execute(query)
records = cursor.fetchall()
update(records)
#3
def import_():
fln = filedialog.askopenfilename(initialdir=os.getcwd(), title="Open Window", filetypes=[('ALL Files', '*.xlsx *.xlsm *.sxc *.ods *.csv *.tsv')])
with open(fln) as myfile:
csvread = csv.reader(myfile, delimiter=',')
for i in csvread:
mydata.append(i)
update(mydata)
for i in mydata:
uid = i[0]
fname = i[1]
lname = i[2]
age = i[3]
date = i[4]
query = "INSERT INTO demo(id, first_name, last_name, age, date) VALUES(NULL, %s, %s, %s, NOW())"
cursor.execute(query, (fname, lname, age))
db.commit()
clear()
#4
def export_():
if len(mydata) < 1:
messagebox.showerror("Error Window", "No data avaliable to export")
return False
fln = filedialog.asksaveasfilename(initialdir=os.getcwd(), title="Save Window", filetypes=(("CSV File", "*.csv"),("XLSX File","*.xlsx")))
with open(fln, mode='w', newline='') as myfile:
exp_writer = csv.writer(myfile, delimiter=',')
for i in mydata:
exp_writer.writerow(i)
messagebox.showinfo("Data Exported", "Your data has been exported to "+os.path.basename(fln)+" successfully.")
#section my window:
section1 = LabelFrame(root, text="Customer List Section")
section1.pack(fill="both", expand="yes", padx=20, pady=10)
# define my treeview:
trv= ttk.Treeview(section1, columns=(1,2,3,4,5), show="headings", height="6")
trv.pack()
trv.heading(1, text="ID")
trv.heading(2, text="First Name")
trv.heading(3, text="Last Name")
trv.heading(4, text="Age")
trv.heading(5, text="Date")
#Display the columns in database:
query = "SELECT * from demo" # demo is name of the table
cursor.execute(query)
records = cursor.fetchall()
update(records)
#make the buttons:
expbtn = Button(section1, text="Export File", command=export_)
expbtn.pack(side=tk.LEFT, padx=10, pady=10)
impbtn = Button(section1, text="Import File", command=import_)
impbtn.pack(side=tk.LEFT, padx=10, pady=10)
root.title("Demo")
root.geometry("2000x1000")
root.mainloop()
'''
如果你不想要 csv,你就不要 csv 模塊。 使用pip
安裝xlsxwriter
模塊並改用它。
我建議將sqlalchemy
和openpyxl
與pandas
一起使用,它們要簡單得多。 以下是加載數據的代碼的樣子:
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('mysql://root:S@mY2829@localhost/sample')
mydata = pd.read_sql('SELECT * FROM demo', engine)
然后,您可以使用mydata.itertuples()
或mydata.todict()
來填充屏幕表單。
保存到 Excel 也很簡單: mydata.to_excel(filename, index=False)
。 請注意,必須安裝openpyxl
package,因為它已在引擎蓋下使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.