Skip to main content
 首页 » 编程设计

python之如何使用 Tkinter 创建文件选择器

2024年10月24日15sharpest

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

请您参考如下方法:

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