Home > other >  How to apply selecting a file button in python
How to apply selecting a file button in python

Time:03-02

I learned how to create a select file button but I don't know how to apply it to the code as you can see below.

from openpyxl import Workbook
# import copy

wb = Workbook()

with open('chat_20220222152420.txt', encoding='utf-8') as sherr:
    row = 1
    column = 1
    ws = wb.active
    for line in sherr:
        if column == 1:
            ## split the line and rejoin
            value = " ".join(line.strip().split(' ')[2:])
        else:
            value = line.strip()
            
        ws.cell(row=row, column=column, value=value)
        
        if (column := column   1) > 3:
            row  = 1
            column = 1
            
    wb.save('Chatchatchat.xlsx')

Instead of using the with open(), I wanted to use a button to choose the file I wanted to open. Below is the code I tried for selecting a file. I just don't know how to apply it in the above code :'(

from ipywidgets import Button
from tkinter import Tk, filedialog
from IPython.display import clear_output, display

def select_files(b):
    
    root = Tk()
    root.withdraw()                                       # Hide the main window.
    root.call('wm', 'attributes', '.', '-topmost', True)  # Raise the root to the top of all windows.
    b.files = filedialog.askopenfilename(multiple=False)  # List of selected files will be set button's file attribute.
    print(b.files)                                        # Print the list of files selected.
    
fileselect = Button(description="File select")
fileselect.on_click(select_files)

display(fileselect)

CodePudding user response:

One way to do this is to move the first block of code into a function that takes a filename to read:

from openpyxl import Workbook

def write_spreadsheet(filename):
    wb = Workbook()
    with open(filename, encoding='utf-8') as sherr:
        row = 1
        # ...

Then call it from select_files (note that filedialog.askopenfilename returns a single filename, not a list):

def select_files(b):
    root = Tk()
    root.withdraw()                                       # Hide the main window.
    root.call('wm', 'attributes', '.', '-topmost', True)  # Raise the root to the top of all windows.
    file = filedialog.askopenfilename(multiple=False)     # Ask the user to select a file.
    print(file)                                           # Print the file selected.
    write_spreadsheet(file)                               # Process the file.
  • Related