【发布时间】:2020-12-28 13:07:41
【问题描述】:
我刚刚开始学习 Python,我正在尝试在 tkinter 中实现这一目标:
- 让用户在任何目录位置选择任意多个文件并将其存储在另一个文件夹中
我不确定是否还有其他更有效的方法,但我已尝试通过以下方式解决此问题:
- 让用户输入他们正在搜索的文件数量(我将 2 设为默认值)
- 遍历文件数量并要求用户选择文件
- 将所有文件发送到新位置
问题是我无法让存储文件和循环正常工作。代码如下:
import tkinter as tk
from tkinter import filedialog, ttk
import shutil
class Getfiles():
def __init__(self):
# initialising the screen name, size title and icon
root = tk.Tk()
root.geometry('450x100')
root.resizable(0, 0)
root.configure(bg='#002060')
# initialising integer value to pass to select_files method
self.var = tk.IntVar()
self.var.set('2')
# Initialising the frame to insert our widget
frame_three = tk.Frame(root, bg='#002060')
frame_three.pack(side='top', fill='both')
# setting label to tell user to input no. of files
num_label = ttk.Label(frame_three, text='No. of files: ', background='#002060', foreground='white')
num_label.pack(side='left', padx=(40, 10), pady=(20, 20))
# setting number of files user wants to fetch
files_num = ttk.Entry(frame_three, width=3, textvariable=self.var)
files_num.pack(side='left', padx=(10, 40), pady=20)
# get user to select the files listed
select_button = ttk.Button(frame_three, text='Select files', width=30, command=self.select_files)
select_button.pack(side='left', padx=(50, 10))
root.mainloop()
def select_files(self):
file_list = []
for i in range(self.var.get()):
file_chosen = filedialog.askopenfilenames(title='Choose a file')
file_list = list(file_chosen)
list += file_list
self.copy(file_list)
def copy(self, file_list):
destination = filedialog.askdirectory()
for file in file_list:
shutil.copy(file, destination)
if __name__ == '__main__':
Getfiles()
【问题讨论】:
-
所有文件(最初)是否都存储在同一个目录中(在将它们移动到新目录之前)?
-
不一定
-
好吧,当他们在同一个目录中时,我有一个答案。现在写答案,并将添加有关如何在不在正常目录中的情况下实施它的信息。
标签: python python-3.x tkinter filedialog