我想出了这个密码:
import tkinter
from tkinter.filedialog import askopenfilename
def browse():
inputfilename=askopenfilename()
return inputfilename
def fileManipulator(infile=browse(),outfile="C:\\out\\File.kml"):
#code that manipulates the file here
file.save(outfile)
root=tkinter.Tk()
browseButton=tkinter.Button(root,text="Browse",command=browse)
browseButton.pack()
fileButton=tkinter.Button(root,text="Manipulate file",command=fileManipulator)
fileButton.pack()
root.mainloop()
代码给了我一个有两个按钮的GUI。浏览按钮应该允许用户浏览输入文件。操纵文件按钮应该处理该文件并将文件输出保存到某个地方。在
我面临的问题是browse askopenfilename
函数在我运行脚本。那个发生的原因是我在fileManipulator函数的定义内调用函数。我在fileManipulator中调用函数的原因很明显是因为我想使用askopenfilename作为输入文件返回的路径。在
有没有解决方法可以不立即执行askopenfilename
,但当按下浏览按钮时?在
编辑:当我按下文件操纵器按钮时,我也不希望再次执行browse()函数。在
编辑:对于更新的需求-
如果是这样的话,我想您可以定义某种类型的
global
变量,当调用browse()
时会更新该变量,并使用它。如果全局变量是None
或任何默认值,这意味着您第一次调用file Manipulate
,那么让您的函数调用browse()
方法。示例-原版:
问题是函数的默认参数是在定义函数时执行的(而不是在调用函数时),这是出现诸如可变默认参数之类的GOTCHAs的主要原因,以及您的问题。在
如果您希望能够将
^{pr2}$infile
作为参数发送,并且还能够使用browse()
函数(如果没有提供)。我建议您使用**kwargs
。示例-另一个更简单的方法是使用默认值,例如},则使用
None
左右,然后如果infile
是{browse()
方法-但这与您最初尝试的不同,例如,如果您将函数称为-
fileManipulator(infile=None)
,这将导致browse()
函数被调用。在最后,如果您不需要
infile
/outfile
作为参数,请不要将它们定义为默认参数,而是在函数体中定义它们-来自documentation -的相关部分
我遇到了同样的问题这是我的解决办法:
相关问题 更多 >
编程相关推荐