这可能是一个愚蠢的问题,但我是使用Python编程的新手。我已经进行了研究,但找不到我的Funcion'openFile(self,file)'未找到的原因。
这是一个简单的Tkinter程序,我需要在其中创建一个Excel文件,并在创建文件后自动将其打开。 (我自己的项目)
当我删除函数“ openFile”时,将正确创建Excel文件。一旦添加'openFile'函数,就会出现“名称未定义”的感觉,好像它不存在一样。我一直无法弄清为什么会发生这种情况。
感谢您的帮助!
from tkinter import *
from tkinter import Text, filedialog
from openpyxl import Workbook, load_workbook
class notepad:
def __init__(self, window):
self.root = window
self.menubar = Menu(self.root)
self.root.config(menu = self.menubar)
self.fileMenu = Menu(self.menubar, tearoff =0)
self.menubar.add_cascade(label = "File", menu = self.fileMenu)
self.fileMenu.add_command(label = "New", command = self.New_File)
self.fileMenu.add_command(label = "Open")
self.fileMenu.add_command(label = "Exit")
name = Label(self.root, text = "Name")
name.grid(row = 1, column = 1)
lname = Label(self.root, text = "Last Name")
lname.grid(row = 2, column = 1)
phone = Label(self.root, text = "Phone number")
phone.grid(row = 3, column = 1)
tname = StringVar()
tlname = StringVar()
tphone = StringVar()
self.namebox = Entry(self.root, textvariable = tname)
self.namebox.grid(row = 1, column = 2)
self.lnamebox = Entry(self.root, textvariable =tlname )
self.lnamebox.grid(row = 2, column = 2)
self.phonebox = Entry(self.root, textvariable = tphone)
self.phonebox.grid(row = 3, column = 2)
self.button = Button(self.root, text = "Save")
self.button.grid(row = 4, columnspan = 3)
def New_File(self):
raw_file_name = filedialog.asksaveasfilename(initialdir = "/Excel_File_Test", title = "Select
Directory", filetypes = (('Excel File', '*.xlsm'),("All Fiesl","*.*")))
raw_file_name = raw_file_name +'.xlsx'
workbook = Workbook()
sheet = workbook.active
sheet ["A1"] = "Name"
sheet ["B1"] = "Last Name"
workbook.save(filename = raw_file_name)
openFile(raw_file_name)
def openFile(self,file):
with load_workbook(filename =file) as workbook:
print(workbook + " has load up correctly") #this message just to confirm the file loads correctly
window = Tk()
application = notepad(window)
window.mainloop()
这可能是一个愚蠢的问题,但我是使用Python编程的新手。我已经进行了研究,但找不到我的Funcion'openFile(self,file)'未找到的原因。这是一个简单的Tkinter ...
用openFile(raw_file_name)
替换self.openFile(raw_file_name)
,该错误将消失。
函数openFile
是您课程的一部分。您应该参考self.openFile
: