简体   繁体   English

Tkinter 文件对话框清除以前的输入

[英]Tkinter filedialog clearing previous input

I just started programming with Python and I'm trying to create a GUI using tkinter where it would ask the user to select a zip file and file destination to send it to after extracting.我刚开始用 Python 编程,我正在尝试使用tkinter创建一个 GUI,它会要求用户选择一个 zip 文件和文件目的地,以便在提取后将其发送到。 What I have noticed is that when a user re-enters a destination, it would still store the previous file directory as well.我注意到的是,当用户重新输入目的地时,它仍然会存储以前的文件目录。 How do I prevent this?我如何防止这种情况?

import tkinter as tk
from tkinter import filedialog

# Setting the window size
screenHeight = 450
screenWidth = 350

root = tk.Tk()


# get the location of the zip file
def input_dir():
    input_filedir = filedialog.askopenfilename(initialdir='/', title='Select File',
                                                filetypes=(("zip", "*.zip"), ("all files", "*.*")))
    my_label.pack()
    return input_filedir


# get location of destination for file 
def output_dir():
    output_filename = filedialog.askdirectory()


# Setting the canvas size to insert our frames
canvas = tk.Canvas(root, height=screenHeight, width=screenWidth)
canvas.pack()

# Setting the frame size to insert all our widgets
frame = tk.Frame(root, bg='#002060')
frame.place(relwidth=1, relheight=1)

# button to get user to chose file directory
openFile = tk.Button(frame, text='Choose the file path you want to extract', command=input_dir)
openFile.pack(side='top')

# button to get destination path 
saveFile = tk.Button(frame, text="Chose the location to save the file", command=output_dir)
saveFile.pack(side='bottom')

extractButton = tk.Button(frame, text="Extract Now")


root.mainloop()

I have tried adding this line of code in the def input_dir function but it changed the positioning of the buttons.我曾尝试在def input_dir函数中添加这行代码,但它改变了按钮的位置。 I'm still working on the code for extracting the zip.我仍在研究用于提取 zip 的代码。

for widget in frame.winfor_children():
    if isinstance(widget, tk.Label):
        widget.destroy()

The files/directories the user clicks are not saved really.用户单击的文件/目录并未真正保存。 Your variables input_filedir and output_filename are garbage collected when their respective functions are completed.您的变量 input_filedir 和 output_filename 在它们各自的功能完成时被垃圾收集。 If you are talking about how the dialog boxes go back to the most recent places opened in a dialog, that is not really something you can mess with too much.如果您正在谈论对话框如何返回到对话框中最近打开的位置,那么您真的不会把它搞得一团糟。 The easy answer is you can add the keyword 'initialdir' when you make the dialog to just pick where it goes like this:简单的答案是,您可以在对话框中添加关键字“initialdir”以选择它的位置,如下所示:

output_filename = filedialog.askdirectory(initialdir='C:/This/sort/of/thing/')

The long answer is that filedialog.askdirectory actually creates an instance of filedialog.Directory and in that class, it saves that information for later in a method called _fixresult (but that method also does other things that are important.) You could overwrite this by doing something like this:长的答案是 filedialog.askdirectory 实际上创建了一个 filedialog.Directory 的实例,并且在该类中,它将该信息保存在名为 _fixresult 的方法中以备后用(但该方法还执行其他重要的事情。)您可以通过以下方式覆盖它做这样的事情:

class MyDirectory(filedialog.Directory):
    def _fixresult(self, widget, result):
        """
        this is just a copy of filedialog.Directory._fixresult without
        the part that saves the directory for next time
        """
        if result:
            # convert Tcl path objects to strings
            try:
                result = result.string
            except AttributeError:
                # it already is a string
                pass
        self.directory = result # compatibility
        return result

def askdirectory (**options):
    "Ask for a directory, and return the file name"
    return MyDirectory(**options).show()

and then using your own askdirectory function instead of filedialog.askdirectory, but that is really convoluted so I recommend using initialdir instead if you can.然后使用你自己的 askdirectory 函数而不是 filedialog.askdirectory,但这真的很复杂,所以如果可以的话,我建议使用 initialdir。

PS When a button is clicked, it calls the function you set after "command=" when you made the button; PS当一个按钮被点击时,它会调用你制作按钮时“command=”后面设置的函数; it seems you got that.看来你明白了。 But these functions are 'void', in that their return is just ignored.但是这些函数是“无效的”,因为它们的返回值被忽略了。 That is to say, the "return input_filedir" line does nothing.也就是说,“return input_filedir”行什么也不做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM