簡體   English   中英

我正在嘗試使用 tkinter 制作一個 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

我的主要問題是:

  1. 我想導出和導入 *.xlsx 擴展名 *而不是.csv
  2. 我想導出帶有標題的單獨列。
  3. 我不想將我的數據導出到以逗號分隔的數據文件。
    編輯:我導入 xlsxwriter 后會發生什么。 注意:我不想從 mysql 導入我想導入到 mysql。

這是我的代碼:

'''

#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模塊並改用它。

我建議將sqlalchemyopenpyxlpandas一起使用,它們要簡單得多。 以下是加載數據的代碼的樣子:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM