Python: file selection interface and folder selection interface

Python itself has no built-in folder selection interface. However, third-party libraries can be used to implement the ability to select files or folders in code. A commonly used library is tkinter, which is one of Python's standard GUI libraries and provides functionality for creating simple graphical user interfaces.

  • Installation: tkinter is one of Python's standard libraries and is usually pre-installed in most Python distributions. If tkinter is not installed in your environment, you may need to install it. On most operating systems, tkinter can be installed from the command line by running the following command:pip install tkinter
  • Remarks: The difference between selecting a file and a folder, one is calling filedialog.askopenfilename(), the other is calling filedialog.askdirectory(), and the rest.

(1) File selection interface

insert image description here

import tifffile		# 用于打开.tif格式的图像
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()		# 创建根窗口
root.withdraw()  	# 隐藏根窗口
file_path = filedialog.askopenfilename()		# 打开文件选择对话框
print("Selected file path:", file_path)			# 打印所选文件的路径

image_stack = tifffile.imread(image_path)       # 加载tif图像

(2) Folder selection interface

insert image description here

import tifffile		# 用于打开.tif格式的图像
import tkinter as tk
from tkinter import filedialog

root = tk.Tk()		# 创建根窗口
root.withdraw()  	# 隐藏根窗口
folder_path = filedialog.askdirectory()			# 打开文件夹选择对话框
print("Selected folder path:", folder_path)		# 打印所选文件夹的路径

# 读取文件夹中的所有tif图像并将它们存储在列表中
image_list = []		# 新建一个空列表
for filename in sorted(os.listdir(folder_path)):				# 列举文件夹中的所有文件 + 排序后遍历。
    if filename.endswith('.tif'):								# 提取以.tif结尾的图像文件。
        image_path = os.path.join(folder_path, filename)		# 将文件名和文件夹路径连接起来,得到完整的图像文件路径image_path
        image = tifffile.imread(image_path)						# 加载tif图像
        image_list.append(image)								# 在列表末尾添加元素

image_stack = np.stack(image_list, axis=0)				# 将图像列表转换为三维数组
labeled_image = labeled_image.astype(np.uint8)          # 将数据类型转换为uint8
tifffile.imwrite(output_tif_path, labeled_image)        # 保存图像为TIFF并指定数据类型为uint8

Guess you like

Origin blog.csdn.net/shinuone/article/details/131529248