实施UI Tkinter时遇到问题

时间:2020-07-03 10:33:16

标签: python python-3.x tkinter

首先,我做了一个脚本来过滤特定文件夹中的文件,然后将所选文件复制并粘贴到另一个文件夹中,

现在我在实现UI Tkinter时遇到问题,当原始文件夹路径和文件类型选择来自界面时,我找不到一种可行的方法。

如果有人告诉我怎么做,我将不胜感激。

以下不带界面的脚本(此脚本可以正常工作):


import os
import shutil


folder_path = "/home/flavio/Projects/FilesOrganizer/test_folder/"
dest_path = "/home/flavio/Projects/FilesOrganizer/paste_dir/"


def images():
    return [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg", ".heif", ".psd"]


def videos():
    return [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng", ".qt", ".mpg", ".mpeg", ".3gp", ".mkv"]


def audio():
    return [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3", ".msv", "ogg", "oga", ".raw",
            ".vox", ".wav", ".wma"]


def documents():
    return [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods", ".odt", ".pwi", ".xsn",
            ".xps", ".dotx", ".docm", ".dox", ".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx",
            ".ppt", "pptx", ".txt", ".in", ".out", ".pdf"]


def other():
    return []


def invalid_opt():
    print("Invalid choice")


options = {
    "a": ["Filter Images", images],
    "b": ["Filter Videos", videos],
    "c": ["Filter Audio", audio],
    "d": ["Filter Documents", documents],
    "e": ["Filter Others", other]
}

for option in options:
    print(option + ") " + options.get(option)[0])

choice = input("Please make Your choice: ")

val = options.get(choice)

# take the function from val
f_val = val[1]


def filter():
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(tuple(f_val())):
                fl = [os.path.join(root, file)]
                for i in fl:
                    yield i


def filter_files_and_move():
    filtered_files = filter()
    for i in filtered_files:
        shutil.copy(i, dest_path)
        print(i)


filter_files_and_move()

这是带有tkinter界面的脚本,我无法使用:

from tkinter import *
from tkinter import filedialog
from tkinter.ttk import *
from tkinter import ttk
import os
import shutil


# path interface
root = Tk()
# root.geometry('350x200')
root.title("Tkinter Dialog Widget")
root.minsize(640, 400)

def browsefunc():
    folderpath = filedialog.askdirectory()
    pathlabel.config(text=folderpath)
    print(str(folderpath))

browsebutton = Button( text="Browse", command=browsefunc)
browsebutton.pack(side="top", padx=20, pady=20)

pathlabel = Label()
pathlabel.pack()

v = StringVar()
# v.set(None)


def images():
    return [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg", ".heif", ".psd"]


def videos():
    return [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng", ".qt", ".mpg", ".mpeg", ".3gp", ".mkv"]


def audio():
    return [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3", ".msv", "ogg", "oga", ".raw",
            ".vox", ".wav", ".wma"]


def documents():
    return [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods", ".odt", ".pwi", ".xsn",
            ".xps", ".dotx", ".docm", ".dox", ".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx",
            ".ppt", "pptx", ".txt", ".in", ".out", ".pdf"]


def other():
    return []


def invalid_opt():
    print("Invalid choice")

options = {
    "a": ["Filter Images", images],
    "b": ["Filter Videos", videos],
    "c": ["Filter Audio", audio],
    "d": ["Filter Documents", documents],
    "e": ["Filter Others", other]
}


for (text, value) in options.items():
    Radiobutton(root, text=text, variable=v,
                value=value).pack(side=TOP, ipady=5)

# Created a function that runs every time the button gets clicked (see the command=quitbutton in the Button widget) and gets the value of the button that is selected
def quitbutton():
    print(v.get())
    # master.quit() uncomment this line if you want to close the window after clicking the button

# Changed the function which gets called by changing the word after command=
quit_btn = Button(root, text="Choose", command=quitbutton, width=10)
quit_btn.pack()

quit = ttk.Button( text="Confirm", command=quit)
quit.pack(side="bottom", padx=20, pady=20)

mainloop()

# ---------------------------

folder_path = str(browsefunc())
# folder_path = "/home/flavio/Projects/FilesOrganizer/test_folder/"
dest_path = "/home/flavio/Projects/FilesOrganizer/paste_dir/"
cwd = os.getcwd()

for option in options:
    print(option + ") " + options.get(option)[0])

choice = str(quitbutton())
# choice = input("Please make Your choice: ")

val = options.get(choice)

# take the function from val
f_val = val[1]


def filter():
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            if file.endswith(tuple(f_val())):
                fl = [os.path.join(root, file)]
                for i in fl:
                    yield i


def filter_files_and_move():
    filtered_files = filter()
    for i in filtered_files:
        shutil.copy(i, dest_path)
        print(i)

谢谢。

1 个答案:

答案 0 :(得分:3)

我已经根据您的代码创建了一个有效的版本。我已经在代码中添加了注释作为描述。可能是这种方式,因为您的代码很长,而且问题出在不同的地方,所以更改更容易理解。

工作代码:

from tkinter import *
from tkinter import filedialog
from tkinter.ttk import *
import os
import shutil


# path interface
root = Tk()
# root.geometry('350x200')
root.title("Tkinter Dialog Widget")
root.minsize(640, 400)

# These global variables will store the selected path and filter.
selected_path = None
selected_filter = None

def browsefunc():
    global selected_path  # Use global variable.
    folderpath = filedialog.askdirectory()
    pathlabel.config(text=folderpath)
    selected_path = str(folderpath)  # Set the selected path.
    print(str(folderpath))

browsebutton = Button( text="Browse", command=browsefunc)
browsebutton.pack(side="top", padx=20, pady=20)

pathlabel = Label()
pathlabel.pack()

v = StringVar()
# v.set(None)


def images():
    return [".jpeg", ".jpg", ".tiff", ".gif", ".bmp", ".png", ".bpg", "svg", ".heif", ".psd"]


def videos():
    return [".avi", ".flv", ".wmv", ".mov", ".mp4", ".webm", ".vob", ".mng", ".qt", ".mpg", ".mpeg", ".3gp", ".mkv"]


def audio():
    return [".aac", ".aa", ".aac", ".dvf", ".m4a", ".m4b", ".m4p", ".mp3", ".msv", "ogg", "oga", ".raw",
            ".vox", ".wav", ".wma"]


def documents():
    return [".oxps", ".epub", ".pages", ".docx", ".doc", ".fdf", ".ods", ".odt", ".pwi", ".xsn",
            ".xps", ".dotx", ".docm", ".dox", ".rvg", ".rtf", ".rtfd", ".wpd", ".xls", ".xlsx",
            ".ppt", "pptx", ".txt", ".in", ".out", ".pdf"]


def other():
    return []


def invalid_opt():
    print("Invalid choice")

options = {
    "a": ["Filter Images", images],
    "b": ["Filter Videos", videos],
    "c": ["Filter Audio", audio],
    "d": ["Filter Documents", documents],
    "e": ["Filter Others", other]
}


for (text, value) in options.items():
    Radiobutton(root, text=text, variable=v,
                value=text).pack(side=TOP, ipady=5)  # Value should be the text (Eg.: a, b) because later you will use this key to get the value from "options" dict."

# Created a function that runs every time the button gets clicked (see the command=quitbutton in the Button widget) and gets the value of the button that is selected
def quitbutton():
    global selected_filter  # Use global variable.
    selected_filter = v.get()  # Set selected filter.
    root.quit()  # Should be destroyed the GUI to run the copy part.
    # master.quit() uncomment this line if you want to close the window after clicking the button

# Changed the function which gets called by changing the word after command=
quit_btn = Button(root, text="Choose", command=quitbutton, width=10)
quit_btn.pack()


mainloop()

print("Path: {}".format(selected_path))
print("Filter: {}".format(selected_filter))

# ---------------------------

# folder_path = "/home/flavio/Projects/FilesOrganizer/test_folder/"
dest_path = "/home/flavio/Projects/FilesOrganizer/paste_dir/"
cwd = os.getcwd()

for option in options:
    print(option + ") " + options.get(option)[0])

val = options.get(selected_filter)

# take the function from val
f_val = val[1]


def filter():
    for root, dirs, files in os.walk(selected_path):
        for file in files:
            print(file)
            if file.endswith(tuple(f_val())):
                fl = [os.path.join(root, file)]
                for i in fl:
                    yield i


def filter_files_and_move():
    filtered_files = filter()
    for i in filtered_files:
        shutil.copy(i, dest_path)
        print("Copied file: {}".format(i))


filter_files_and_move()  # Call the cipying function.

测试和输出:

test1文件夹包含一个jpeg文件。

>>> ll test1/
total 8
drwxrwxr-x  2 user user  4096 Jul  3 13:19 ./
drwxrwxr-x 18 user user  4096 Jul  3 13:32 ../
-rw-rw-r--  1 user user  0 Jul  3 13:19 test.jpeg

test2文件夹为空。该文件夹是目的地。

>>> ll test2/
total 8
drwxrwxr-x  2 user user 4096 Jul  3 13:32 ./
drwxrwxr-x 18 user user 4096 Jul  3 13:32 ../

运行代码(选择test1文件夹和a过滤器):

>>> python3 test.py
/home/user/test1
Path: /home/user/test1
Filter: a
a) Filter Images
b) Filter Videos
c) Filter Audio
d) Filter Documents
e) Filter Others
test.jpeg
Copied file: /home/user/test1/test.jpeg

检查test2文件夹:

>>> ll test2/
total 8
drwxrwxr-x  2 user user 4096 Jul  3 13:37 ./
drwxrwxr-x 18 user user 4096 Jul  3 13:37 ../
-rw-rw-r--  1 user user 0 Jul  3 13:37 test.jpeg

如您在上方看到的,脚本按预期工作。