python askopenfilenames使用
时间: 2023-10-05 13:12:56 浏览: 44
`askopenfilenames`是Python的`tkinter`模块中的一个函数,用于弹出一个文件选择对话框,让用户选择一个或多个文件。
使用`askopenfilenames`函数需要先导入`tkinter`模块,然后可以直接调用该函数。下面是一个简单的示例代码:
```python
import tkinter as tk
from tkinter import filedialog
root = tk.Tk()
root.withdraw()
file_paths = filedialog.askopenfilenames()
print(file_paths)
```
代码中,首先创建了一个`tkinter`的根窗口,并隐藏该窗口。然后调用`askopenfilenames`函数,弹出文件选择对话框,并返回用户选择的文件路径列表。最后将选择的文件路径打印出来。
需要注意的是,`askopenfilenames`函数返回的是一个元组,其中包含了用户选择的所有文件的路径。如果用户取消了选择,则返回一个空元组。如果需要获取单个文件的路径,则可以使用`askopenfilename`函数。
相关问题
使用python中的GUI编写一个图片展示界面
您可以使用Python的Tkinter库来创建一个GUI,用于展示图片。以下是示例代码:
``` python
import tkinter as tk
from tkinter import filedialog
from PIL import ImageTk, Image
root = tk.Tk()
root.title("Image Viewer")
# Create a list to hold images
image_list = []
# Function to select images
def select_images():
file_types = (("JPEG files", "*.jpg"), ("PNG files", "*.png"))
file_paths = filedialog.askopenfilenames(filetypes=file_types)
for file_path in file_paths:
# Open image from file path
image = Image.open(file_path)
# Add image to list
image_list.append(image)
# Function to display images
def display_images():
for image in image_list:
# Resize image to fit window
image = image.resize((500, 500), Image.ANTIALIAS)
# Convert image to Tkinter format
img = ImageTk.PhotoImage(image)
# Create label to display image
image_label = tk.Label(root, image=img)
# Display label
image_label.pack()
# Create button to select images
select_button = tk.Button(root, text="Select Images", command=select_images)
select_button.pack()
# Create button to display images
display_button = tk.Button(root, text="Display Images", command=display_images)
display_button.pack()
# Start the GUI
root.mainloop()
```
这段代码创建一个显示窗口,其中有两个按钮:“Select Images”和“Display Images”。点击“Select Images”按钮可选择要显示的一组图片。点击“Display Images”按钮可在窗口中显示所有已选择的图片。您可以根据需要修改此代码以满足您的需求。
python tkinter 文件选择框
Python 的 tkinter 库提供了 `tkinter.filedialog` 模块来创建文件选择框。其中,`askopenfilename()` 函数可以用来打开文件选择框,选择单个文件。`askopenfilenames()` 函数可以用来选择多个文件。`asksaveasfilename()` 函数可以用来打开保存文件对话框,用于保存文件。
示例代码如下:
```
from tkinter import filedialog
from tkinter import *
root = Tk()
root.filename = filedialog.askopenfilename(initialdir = "/", title = "Select file", filetypes = (("Text files", "*.txt*"), ("all files", "*.*")))
print(root.filename)
root.mainloop()
```
上面代码演示了如何使用 `askopenfilename` 函数打开文件选择框,并将选择的文件路径打印出来。