这是我的主文件:
ExcelAppl = win32com.client.Dispatch('Excel.Application')
Workbook = ExcelAppl.Workbooks.Open('excel file path')
Sheet = Workbook.Worksheets.Item(1)
这是 Python GUI :
root = Tk()
def callback():
file_path = tkFileDialog.askopenfilename(filetypes=[("Excel files","*.xls")])
print "the file path %s",file_path
Text_button.insert(INSERT,file_path)
def execute():
execfile("MainLibrary.py")
Browse_button = Button(text='Browse', command=callback).pack(side=LEFT, padx=10, pady=20, ipadx=20, ipady=10)
Execution_button = Button(text='Convert', command=execute).pack(side=BOTTOM, padx=10, pady=20, ipadx=20, ipady=10)
root.mainloop()
这是我的查询。我需要从GUI获取file_path
并将其分配给Workbook = ExcelAppl.Workbooks.Open('excel file path')
。我需要从GUI获取路径并将路径分配给我的主代码。有人可以帮忙吗?
答案 0 :(得分:0)
此处您不需要execfile()
。
您可以在main_library.py
中定义一个函数:
import win32com.client
def do_something_with_excel_file(filename):
app = win32com.client.Dispatch('Excel.Application')
workbook = app.Workbooks.Open(filename)
worksheet = workbook.Worksheets.Item(1)
# use `worksheet` ...
if __name__=="__main__":
import sys
# get filename from command-line if called as a script
do_something_with_excel_file(sys.argv[1])
然后您可以在GUI代码中导入它:
import tkFileDialog
from Tkinter import as tk
import main_library
def browse():
path = tkFileDialog.askopenfilename(filetypes=[("Excel files","*.xls")])
file_path.set(path)
print "the file path %s", path
def convert():
root.destroy() # quit gui
main_library.do_something_with_excel_file(file_path.get())
root = tk.Tk()
file_path = tk.StringVar()
tk.Label(root, textvariable=file_path).pack()
tk.Button(text='Browse', command=browse).pack()
tk.Button(text='Convert', command=convert).pack()
root.mainloop()