关于Tkinter的问题:
我想创建一个浏览以及一个文本显示,它将显示我从浏览按钮中选择的文件。以下是我的代码:
button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}
Tkinter.Button(self, text='Browse and open filename - then manually upload it', command=self.askopenfilename).pack(**button_opt)
self.file_opt = options = {}
options['defaultextension'] = '.txt'
options['filetypes'] = [('all files', '.*'), ('text files', '.txt')]
options['initialdir'] = 'C:\\'
options['initialfile'] = 'myfile.txt'
options['parent'] = root
options['title'] = 'Browse'
self.dir_opt = options = {}
options['initialdir'] = 'C:\\'
options['mustexist'] = False
options['parent'] = root
options['title'] = 'Browse'
image = Image.open("/home/kuber/Downloads/godata/images/header.png")
photo = ImageTk.PhotoImage(image)
label = Label(image=photo)
label.image = photo # keep a reference!
label.place(width=768, height=576)
label.pack(side = TOP)
self.centerWindow()
self.master.columnconfigure(10, weight=1)
#Tkinter.Button(self, text='upload file', command=self.Fname).pack(**button_opt)
self.file_name = Text(self, width=39, height=1, wrap=WORD)
def Fname(self):
self.file_name = Text(self, width=39, height=1, wrap=WORD)
self.file_name.grid(row=1, column=1, columnspan=4, sticky=W)
def askopenfilename(self):
# get filename
filename = tkFileDialog.askopenfilename(**self.file_opt)
# open file on your own
if filename:
with open(self.filename, 'r') as inp_file:
print "1"
self.file_name.delete(0.0, END)
self.file_name.insert(0.0, inp_file.read())
#return open(filename, 'r')
按下浏览按钮并打开文件。我希望从askopenfilename
函数转到文本小部件。但是我得到了错误:
AttributeError: TkFileDialogExample instance has no attribute 'filename'
当我在Fname之外包含self.file_name.grid(row = 1,column = 1,columnspan = 4,sticky = W)时,Tkinter会挂起。
答案 0 :(得分:0)
当你看到像'X实例没有属性'文件名'这样的python错误时,它就意味着它所说的内容。根本原因通常是两件事之一:
所以,问问自己,"为什么TkFileDialogExample没有这个属性?你有没有定义它具有该属性?何时何地?你拼错了吗?或者,您的代码是否应该从其他对象获取属性?
换句话说,您的代码正在使用self.filename
:self
您认为它是什么?