首页 > 解决方案 > 如何将函数的路径分配给使用 openpyxl 创建的 excel?

问题描述

我是 Python 新手,我一直在尝试创建一个函数“save_file()”;它为我提供了保存 Excel 文件的路径,Excel 文件是使用 openpyxl 从列表中创建的,例如:

import openpyxl as opxl
import tkinter as tk


wbk = opxl.Workbook()
worksheet1 = wbk.active
worksheet1.title = 'Species_concentration'
r = 2
for Hyd in Hyd_conc_list:
    worksheet1.cell(row = r, column = 1).value = Hyd
    r += 1

问题是,一旦创建了 Excel,我想将函数“save_file()”作为 tkinter 界面中的命令分配给一个按钮。我这样做了:

def save_file():
    ftype = [('Excel file', '*.xlsx')]
    idir = os.path.join (os.environ ['USERPROFILE'], 'Documents')
    path_name = tk.filedialog.asksaveasfilename (filetypes = ftype, initialdir = idir)
    wbk.save(path_name)    
 
button3 = tk.Button(wdw, text = 'SAVE', bg = 'gray14', bd = 4, fg = 'white', relief = 'raised', command = save_file)

但它不起作用,我将不胜感激,非常感谢。

标签: pythonexcel

解决方案


推荐阅读