繁体   English   中英

Tkinter中的Filedogue错误

[英]Filedialogue error in Tkinter

关于Tkinter的问题:

我想创建一个浏览器以及一个文本显示,它将显示我从浏览按钮中选择的文件。 以下是我的代码:

编辑1。

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会挂起。

当您看到类似“ X实例没有属性'文件名”之类的python错误时,它的含义完全相同。 根本原因通常是两件事之一:

  • X是您打算使用的对象,并且确实没有该属性v(也许您拼错了它,忘记了定义它),或者
  • 您告诉程序使用X,但是X不是您认为的那样(即:您认为X是指特定类型的对象,但它是字符串或数字或其他类。

因此,问自己:“为什么TkFileDialogExample不具有此属性?您是否定义了该属性?何时何地?是否拼写错误?或者,您的代码是否应该从其他对象获取该属性?

换句话说,您的代码正在使用self.filenameself是您认为的样子吗?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM