[英]After I use askopenfilename to get a filename by click a button, how can I show that filename in an Entry in python
Here is my code, so after I click the button, it will call loadFile function, and the file name will be saved in the function, after that how can I change the text of Entry(self.filedir) to that file name? 这是我的代码,因此在单击按钮后,它将调用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()
Add the following two lines to loadFile
: 将以下两行添加到
loadFile
:
self.filedir.delete(0, "end")
self.filedir.insert(0, self.filename)
I have a tkinter class that creates a frame containing a label, entry field to contain the filepath and a browse button to select the file. 我有一个tkinter类,它创建一个包含标签的框架,一个包含文件路径的输入字段和一个用于选择文件的浏览按钮。
Try this simple example (Sorry it is python 2 not python 3 given its age). 试试这个简单的例子(很抱歉,它是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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.