用Tkinter python请求文件路径

时间:2016-11-14 11:01:21

标签: python tkinter

我正在尝试使用askopenfilename()函数获取文件路径,但我无法用所选的文件路径替换我的条目(myEntry)的值

我该如何处理?

我的代码:

from tkinter import *
from tkinter import filedialog

class Window(Tk):
    def __init__ (self,inTitle="FUNCT"):
        Tk.__init__(self)
        self.title(inTitle)
        self.geometry("500x300")
        self.__myEntry = StringVar(self,"E:/TEST.txt")
        pathfile = Entry(self,textvariable = self.__myEntry, width =80)
        pathfile.grid()
        bouton1 = Button(self, text = "Parcourir", command =self.loadfile)
        bouton1.grid()

    def loadfile(inSelf):
        global filename
        inSelf.filename  = filedialog.askopenfilename()
        return inSelf.filename

myWindow = Window()
myWindow.mainloop()

1 个答案:

答案 0 :(得分:0)

您可以直接在按钮的回调中更改filename的值,而不是返回StringVar

def loadfile(self):
    self.__myEntry.set(filedialog.askopenfilename())

或者正如Bryan Oakley在评论中所建议的那样,您可以完全删除StringVar并直接更新Entry

class Window(Tk):
    def __init__ (self,inTitle="FUNCT"):
        Tk.__init__(self)
        self.title(inTitle)
        self.geometry("500x300")
        self.pathfile = Entry(self, width =80)
        self.pathfile.grid()
        self.pathfile.insert(0, "E:/TEST.txt") #inserts default filename
        bouton1 = Button(self, text = "Parcourir", command =self.loadfile)
        bouton1.grid()

    def loadfile(self):
        filename = filedialog.askopenfilename()
        self.pathfile.delete(0,END) #removes current text
        self.pathfile.insert(0,filename) #insert the filename