Use Tkinter to Open file, run script and export file

纵饮孤独 提交于 2021-02-08 10:50:46

问题


I would like to create a pyton script that takes an excel file (provided by the user), run a script, and save this excel file (with a file name provided by the user). I would like to implement some buttons using Tkinter to enable non-programmers to easily use my algorithm.

I tried to create a ''load data'' and ''display data'' button (I took a code online) that both work.

However I didn't manage to run the script on the database imported (as I don't know how to access it)

I didnt manage to create a button that enables the user to choose the name of the file they want to save it to.

import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
import pandas as pd

import csv

# --- classes ---

class MyWindow:

    def __init__(self, parent):

        self.parent = parent

        self.filename = None
        self.df = None

        self.text = tk.Text(self.parent)
        self.text.pack()

        self.button = tk.Button(self.parent, text='LOAD DATA', command=self.load)
        self.button.pack()

        self.button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)
        self.button.pack()
        self.button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)
        self.button.pack()

    def load(self):

        name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xslm', '*.xlsx'))])

        if name:
            if name.endswith('.csv'):
                self.df = pd.read_csv(name)
            else:
                self.df = pd.read_excel(name)

            self.filename = name

             display directly
            self.text.insert('end', str(self.df.head()) + '\n')



    def display(self):
        # ask for file if not loaded yet
        if self.df is None:
            self.load_file()

        # display if loaded
        if self.df is not None:
            self.text.insert('end', self.filename + '\n')
            self.text.insert('end', str(self.df.head()) + '\n')

    #def script_python(self):
       # self.df=self.df.iloc[:, :-1]
       #this is not my original script


    #def file_save(self):
    #    savefile = asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),
         #                               ("All files", "*.*") ))



# --- main ---

if __name__ == '__main__':
    root = tk.Tk()
    top = MyWindow(root)
    root.mainloop()

My python script that do analysis on the excel file works, so I just put a very simple python script to make your life easier.

Thank you I'm new at Tkinter and not used to classes and dictionaries. thanks for your help


回答1:


I've modified your code, adding a button to run your script and a button to save the data (I've tried to keep the rest as close to your original code as possible):

import tkinter as tk
from tkinter import ttk
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import asksaveasfilename
from tkinter.messagebox import showerror
import pandas as pd

import csv

# --- classes ---

class MyWindow:
    def __init__(self, parent):

        self.parent = parent

        self.filename = None
        self.df = None

        self.text = tk.Text(self.parent)
        self.text.pack()

        # load data button
        self.load_button = tk.Button(self.parent, text='LOAD DATA', command=self.load)
        self.load_button.pack()

        # display data button
        self.display_button = tk.Button(self.parent, text='DISPLAY DATA', command=self.display)
        self.display_button.pack()

        # run script button
        self.script_button = tk.Button(self.parent, text='RUN SCRIPT', command=self.script_python)
        self.script_button.pack()

        # save data button
        self.save_button = tk.Button(self.parent, text='SAVE DATA', command=self.file_save)
        self.save_button.pack()

    def load(self):
        name = askopenfilename(filetypes=[('CSV', '*.csv',), ('Excel', ('*.xls', '*.xslm', '*.xlsx'))])

        if name:
            if name.endswith('.csv'):
                self.df = pd.read_csv(name)
            else:
                self.df = pd.read_excel(name)

            self.filename = name

            # display directly
            self.text.insert('end', str(self.df.head()) + '\n')

    def display(self):
        # ask for file if not loaded yet
        if self.df is None:
            self.load_file()

        # display if loaded
        if self.df is not None:
            self.text.insert('end', self.filename + '\n')
            self.text.insert('end', str(self.df.head()) + '\n')

    def script_python(self):
        # replace this with the real thing
        self.df = self.df.iloc[:, :-1]

    def file_save(self):
        fname = asksaveasfilename(filetypes=(("Excel files", "*.xlsx"),
                                        ("All files", "*.*")))
        # note: this will fail unless user ends the fname with ".xlsx"
        self.df.to_excel(fname)


# --- main ---

if __name__ == '__main__':
    root = tk.Tk()
    top = MyWindow(root)
    root.mainloop()


来源:https://stackoverflow.com/questions/58523959/use-tkinter-to-open-file-run-script-and-export-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!