3

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

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

我想在按下确定按钮后打开文件。

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()  
4

1 回答 1

1

你的两个问题是相关的。问题出在你的browsecsv(self)方法上。您directory的已存入self.filename,无需askopenfilename()再次调用。这就是文件浏览器打开两次的原因。此外,要在 中设置文本Entry,您需要为其分配一个文本变量。

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

然后,您可以将其分配给Entry您的方法:

def browsecsv(self):
   from tkFileDialog import askopenfilename
   Tk().withdraw() 
   self.filename = askopenfilename()
   self.entryText.set(self.filename)
于 2017-02-09T08:57:28.603 回答