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

问题描述

我刚刚开始使用Python进行编程,我尝试使用tkinter创建一个GUI,在该GUI中,用户会要求用户选择一个zip文件和解压缩后的文件目标。我注意到的是,当用户重新输入目标位置时,它仍然还会存储先前的文件目录。我该如何预防?

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()

我尝试在def input_dir函数添加此行代码,但它更改了按钮的位置。我仍在研究提取zip的代码

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

解决方法

用户单击的文件/目录并未真正保存。当变量各自的功能完成时,它们的input_filedir和output_filename将被垃圾回收。如果您谈论的是对话框如何返回到对话框中打开的最新位置,那确实不是一件容易的事。简单的答案是,在创建对话框时,您可以添加关键字“ initialdir”,就像这样:

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

长的答案是filedialog.ask目录实际上创建了一个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()

,然后使用您自己的askdirectory函数而不是filedialog.ask目录,但这确实很复杂,因此,我建议如果可以的话,改用initialdir。

P.S。单击按钮时,它会在您创建按钮时调用您在“ command =”之后设置的功能;看来你明白了。但是这些函数是“ void”的,因为它们的返回仅被忽略。也就是说,“ return input_filedir”行没有任何作用。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...