如何在 python 中应用选择文件按钮

How to apply selecting a file button in python

我了解了如何创建 select 文件按钮,但我不知道如何将其应用到代码中,如下所示。

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')

我不想使用 with open(),而是想用一个按钮来选择我想打开的文件。下面是我尝试 selecting 文件的代码。我只是不知道如何在上面的代码中应用它:'(

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)

一种方法是将第一个代码块移动到一个函数中,该函数需要一个文件名来读取:

from openpyxl import Workbook

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

然后从 select_files 调用它(注意 filedialog.askopenfilename returns 单个文件名,而不是列表):

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.