此 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()
最佳答案
你的两个问题是相关的。问题出在您的 browsecsv(self)
方法中。您的目录
已经存储在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)
关于Python GUI (Tkinter) 文件浏览器并说明在空白处选择的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42131397/