这是我的代码,所以单击按钮后,它将调用loadFile函数,文件名将保存在函数中,之后如何将Entry(self.filedir)的文本更改为该文件命名
from tkinter import *
from tkinter.filedialog import askopenfilename
class Checker:
def loadFile(self):
self.filename = askopenfilename(filetypes=(("info", "*.xlsx"), ("all file", "*.*")))
def __init__(self, master):
master.title("Checker")
self.load_button = Button(master, text="load file", command=self.loadFile)
self.load_button.grid(row=0, column=0)
self.filedir = Entry(master, text=" ")
self.filedir.grid(row=0, column=1)
if __name__=='__main__':
root = Tk()
k = Checker(root)
root.mainloop()
答案 0 :(得分:0)
将以下两行添加到loadFile
:
self.filedir.delete(0, "end")
self.filedir.insert(0, self.filename)
答案 1 :(得分:0)
我有一个tkinter类,它创建一个包含标签的框架,包含文件路径的条目字段和一个用于选择文件的浏览按钮。
试试这个简单的例子(抱歉,考虑到它的年龄,它是python 2而不是python 3。)
from Tkinter import *
import tkFileDialog
class FileSelect(Frame):
def __init__(self,master,label,opensave,filetype,**kw):
Frame.__init__(self,master)
self.configure(**kw)
self.file = StringVar()
self.opensave = opensave
self.filetypes = filetype
self.Label = Label(self, text=label)
self.Label.config(width=10,anchor=E)
self.filenamebox = Entry(self,text=self.file)
self.filenamebox.config(width=50)
self.btnBrowse = Button(self,text='Browse',command=self.browse_file)
self.btnBrowse.config(width=10)
self.Label.grid(row=0,column=0,pady=5,sticky=E)
self.filenamebox.grid(row=0,column=1,pady=5)
self.btnBrowse.grid(row=0,column=2,pady=5,padx=5)
def browse_file(self):
filename = []
if self.opensave == "open":
filename = tkFileDialog.askopenfilename(filetypes=self.filetypes)
else:
filename = tkFileDialog.asksaveasfilename(filetypes=self.filetypes)
self.file.set(filename)
def get_filename(self):
return self.file.get()
def main():
root = Tk()
root.title("Select File Example")
selectFile = FileSelect(root,"My File","open",[('All Files','*.*')])
selectFile.grid()
root.mainloop()
if __name__ == '__main__':
main()