我學會了如何創建一個選擇檔案按鈕,但我不知道如何將它應用到代碼中,如下所示。
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()。下面是我嘗試選擇檔案的代碼。我只是不知道如何在上面的代碼中應用它:'(
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)
uj5u.com熱心網友回復:
一種方法是將第一個代碼塊移動到一個讀取檔案名的函式中:
from openpyxl import Workbook
def write_spreadsheet(filename):
wb = Workbook()
with open(filename, encoding='utf-8') as sherr:
row = 1
# ...
然后呼叫它select_files(注意filedialog.askopenfilename回傳單個檔案名,而不是串列):
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.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/436519.html
標籤:Python 按钮 ipywidgets
上一篇:第二次單擊后重置按鈕樣式
