Python tkinter:浏览目录并保存到新目录

Iss*_*c_n 2 python python-3.x

我想通过单击 python tkinker GUI 中的 Button 来打开一个新浏览器,新目录需要保存并显示在 GUI 上。

我可以使用以下命令打开当前目录;

import os
subprocess.Popen('explorer "C:\temp"')
cur_path = os.path.dirname(__file__)
Run Code Online (Sandbox Code Playgroud)

我的问题是如何在上述步骤 A/B 之后保存活动浏览器目录并在 GUI 上显示?

小智 5

First of all, the imports needed for this answer:

import os
import tkinter as tk # if using Python 3
import Tkinter as tk # if using Python 2
Run Code Online (Sandbox Code Playgroud)

Let's say that your button has been defined.

Here is some sample code which will get the current directory:

curr_directory = os.getcwd() # will get current working directory
Run Code Online (Sandbox Code Playgroud)

If you're looking to set up a GUI to ask the user to select a file, use:

name = tkinter.tkFileDialog.askopenfilename(initialdir = curr_directory,title = "Select file",filetypes = (("jpeg files","*.jpg"),("all files","*.*")))
print(name)
Run Code Online (Sandbox Code Playgroud)

Which will store the file that they have chosen, with the directory they start at set to curr_directory which is the current directory.

If you are instead looking to set up a GUI in which the user chooses a directory, you can use:

dir_name = tk.tkFileDialog.askdirectory()
Run Code Online (Sandbox Code Playgroud)

This will store the name of the directory they have chosen in the dir_name variable.

For more information, check out this link on how to use the file dialog. Alternatively, you can check the general tkinter documentation here (for Python 2) and here (for Python 3). If you need a reference to the file dialog, this is a good source.