如何在python中应用选择文件按钮
我学习了如何创建选择文件按钮,但我不知道如何将其应用到代码中,如下所示。
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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实现此目的的一种方法是将第一个代码块移动到需要读取文件名的函数中:
然后从
select_files
调用它(请注意,filedialog.askopenfilename
返回一个单个文件名,而不是列表):One way to do this is to move the first block of code into a function that takes a filename to read:
Then call it from
select_files
(note thatfiledialog.askopenfilename
returns a single filename, not a list):