可以的,你可以将 `wb` 对象作为 `choose_file()` 函数的返回值,然后在调用 `choose_file()` 函数时获取该对象,并在外部进行操作。以下是修改后的代码:
```python
from tkinter import *
from tkinter import filedialog
import xlwings as xw
def choose_file():
file_path = filedialog.askopenfilename()
print(file_path)
app = xw.App()
wb = app.books.open(file_path)
return wb
root = Tk()
button = Button(root, text="Choose File", command=choose_file)
button.pack()
root.mainloop()
# 在主程序中获取 wb 对象并进行操作
wb = choose_file()
names = wb.sheets['Sheet1'].range('d2:d12').value
wb.close()
app = wb.app
app.quit()
for n in names:
print(n)
```
这个程序会创建一个窗口,并在窗口中添加一个“Choose File”按钮。当用户点击按钮时,会弹出一个文件选择对话框,用户可以在其中选择一个 Excel 文件。选择完毕后,程序会打印出该文件中 Sheet1 的 D2:D12 单元格范围内的所有值。