【问题标题】:How do I create a file chooser using Tkinter?如何使用 Tkinter 创建文件选择器?
【发布时间】:2015-09-04 19:05:31
【问题描述】:

我一直在尝试使用 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()

【问题讨论】:

  • 不要把()放在askopenfilename之后。
  • 另外,不要链接.grid(),否则您最终会将None 保存到this.button3。此外,我建议坚持使用标准 self 而不是使用 this
  • 好吧,好像已经解决了。谢谢!

标签: python user-interface button tkinter filechooser


【解决方案1】:
  1. 技术上没有要求,但您应该使用标准的self 而不是this
  2. 类似a = Button(root).grid() 的东西将grid() 的结果保存到a,所以现在a 将指向None。首先创建和分配小部件,然后在单独的语句中调用几何管理器(grid() 等)。
  3. 小部件的command 是小部件在请求时将调用的函数。假设我们定义了def search_for_foo(): ...。现在search_for_foo 是一个函数。 search_for_foo()search_for_foo 编程为 return 的任何内容。这可以是数字、字符串或任何其他对象。它甚至可以是一个类、类型或函数。但是,在这种情况下,您只需使用普通的command=filedialog.askopenfilename。如果您需要将参数传递给小部件的回调函数,有办法做到这一点。

【讨论】:

    【解决方案2】:

    改变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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-25
      • 2020-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-14
      • 1970-01-01
      相关资源
      最近更新 更多