Python 如何使用Tkinter创建文件选择器?

Python 如何使用Tkinter创建文件选择器?,python,user-interface,button,tkinter,filechooser,Python,User Interface,Button,Tkinter,Filechooser,我一直在尝试使用Tkinter创建一个文件选择器。我想让它发生时,“选择文件”按钮被按下。但是,问题是它会自动打开,而不是在单击按钮后打开GUI然后创建文件目录窗口。我没有正确地创建它吗 #Creates the Top button/label to select the file this.l5 = Label(this.root,text = "Boxes File:").grid(row = 0, column = 0) this.filename = StringVar() this.

我一直在尝试使用Tkinter创建一个文件选择器。我想让它发生时,“选择文件”按钮被按下。但是,问题是它会自动打开,而不是在单击按钮后打开GUI然后创建文件目录窗口。我没有正确地创建它吗

#Creates the Top button/label to select the file
this.l5 = Label(this.root,text = "Boxes File:").grid(row = 0, column = 0)
this.filename = StringVar()
this.e3 = Entry(this.root,textvariable = this.filename)
this.button3 = Button(this.root,text = "Select File",command=filedialog.askopenfilename()).grid(row = 0, column = 7)
mainloop()
  • 这在技术上不是必需的,但是您应该使用标准的
    self
    ,而不是
    this
  • 类似于
    a=Button(root).grid()
    grid()
    的结果保存到
    a
    ,因此现在
    a
    将指向
    None
    。首先创建并分配小部件,然后在单独的语句中调用几何体管理器(
    grid()
    ,等等)
  • 小部件的
    命令是小部件在被请求时将调用的函数。假设我们已经定义了
    defsearch\u for_foo():…
    。现在
    搜索\u foo
    是一个函数
    search\u for_foo()
    search\u for_foo
    编程为
    return
    的内容。这可以是数字、字符串或任何其他对象。它甚至可以是类、类型或函数。但是,在这种情况下,您只需使用普通的
    命令=filedialog.askopenfilename
    。如果您需要将参数传递给小部件的回调函数,有几种方法可以做到这一点

  • 更改button3的命令属性。这对我有用

    #Creates the Top button/label to select the file
    this.l5 = Label(this.root,text = "Boxes File:").grid(row = 0, column = 0)
    this.filename = StringVar()
    this.e3 = Entry(this.root,textvariable = this.filename)
    # Insert "lambda:" before the function
    this.button3 = Button(this.root,text = "Select 
    File",command=lambda:filedialog.askopenfilename()).grid(row = 0, column = 7)
    mainloop()
    

    不要将
    ()
    放在
    askopenfilename
    之后。另外,不要将
    .grid()
    链接起来,否则将
    保存到
    此.button3
    。此外,我建议坚持使用标准的
    self
    ,而不是使用
    this
    。好吧,似乎这样就解决了它。谢谢