Tkinter .withdraw() strange behaviour
<p>Using the following code, the Tkinter root window will be hidden: </p>

<pre><code>def main():
    root = Tkinter.Tk()
    root.iconify()
    a = open(tkFileDialog.askopenfilename(), 'r')

main()
</code></pre>

<p>However, using this variation, the root window will not be hidden: </p>

<pre><code>class Comparison:
    def __init__(self, file=open(tkFileDialog.askopenfilename(),'r')):
        self.file = file
        self.length = sum(1 for _ in self.file)

def main():
    root = Tkinter.Tk()
    root.iconify()
    a = Comparison()

main()
</code></pre>

<p>Why does calling <code>tkFileDialog.askopenfilename</code> with the constructor cause this behaviour? I have tried both <code>root.withdraw()</code> and <code>root.iconify()</code> and experienced the same behaviour. </p>

<p>It may be worth noting that I am on OSX 10.11.6.</p>

<p>Thanks!</p>

<p>When you do this:</p>

<pre><code>def __init__(self, file=open(tkFileDialog.askopenfilename(),'r')):
</code></pre>

<p>That <em>immediately</em> runs <code>open(tkFileDialog.askopenfilename(),'r')</code>, because default arguments are evaluated when the function is defined. Therefore, when you run the second code block, the interpreter creates a necessary Tkinter root window and opens that file chooser while it's still defining that class. <em>After</em> that, you define a function <code>main</code>. Finally, you call <code>main()</code>, which creates a root object, withdraws it, and instantiates an object of the <code>Comparison</code> class. The root window you explicitly created with <code>root = Tkinter.Tk()</code> <em>is</em> hidden. The older one, that Python was forced to create in order for the file dialog to exist, however, was not.</p>

<p>To fix this, put the default behavior into the method body rather than its signature:</p>

<pre><code>class Comparison:
    def __init__(self, file=None):
        if file is None:
            self.file = open(tkFileDialog.askopenfilename(),'r')
        else:
            self.file = file
        self.length = sum(1 for _ in self.file)
</code></pre>

python python-2.7 tkinter