Python GUI(Tkinter)文件浏览器并说明在空白处选择的文件

此GUI允许用户打开文件浏览器并选择所需的文件,将其显示在空白字段上,然后在按下打开后打开文件.我是
python的新手,并尝试在self.filename上放置print tkFileDialog.askopenfilename(),但这会导致语法错误.请帮忙.谢谢!

我的问题如下:
1)为什么我的文件浏览器在按下“文件浏览器”按钮后打开两次.
2)另外,如何在文件空白而不是python命令提示符中声明所选文件的目录?

按ok按钮后,我想将来打开文件.

from Tkinter import *
import csv
import tkFileDialog
class Window:       
 def __init__(self, master):     
    self.filename=""
    csvfile=Label(root, text="Load File:").grid(row=1, column=0)
    bar=Entry(master).grid(row=1, column=1) 

    #Buttons  
    y=12
    self.cbutton= Button(root, text="OK", command=self.process_csv) #command refer to process_csv
    y+=1
    self.cbutton.grid(row=15, column=3, sticky = W + E)
    self.bbutton= Button(root, text="File Browser", command=self.browsecsv) #open browser; refer to browsecsv
    self.bbutton.grid(row=1, column=3)

 def browsecsv(self):
    from tkFileDialog import askopenfilename
    Tk().withdraw() 
    self.filename = askopenfilename()
    print tkFileDialog.askopenfilename() # print the file that you opened.

 def callback():
    abc = askopenfilename()
    execfile("input.xlsx")

 def process_csv(self):
    if self.filename:
        with open(self.filename, 'rb') as csvfile:
            logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
            rownum=0

            for row in logreader:    
                NumColumns = len(row)        
                rownum += 1

            Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)] 

root = Tk()
window=Window(root)
root.mainloop()  

最佳答案 你的两个问题都是相关的.问题出在您的browsecsv(self)方法中.您的目录已存储在self.filename中,无需再次调用askopenfilename().这就是文件浏览器打开两次的原因.此外,要在条目中设置文本,您需要为其分配一个文本变量.

self.entryText = StringVar()
self.bar = Entry(root, textvariable=self.entryText ).grid(row=1, column=1)

然后,您可以将其分配给方法中的条目:

def browsecsv(self):
   from tkFileDialog import askopenfilename
   Tk().withdraw() 
   self.filename = askopenfilename()
   self.entryText.set(self.filename)
点赞