Importing from a Package in IDLE vs Shell
Asked Answered
S

1

1

Importing a whole package works in IDLE, but not in shell. The following works fine in IDLE:

import tkinter as tk
tk.filedialog.askopenfilename()

In shell, I get this error:

AttributeError: 'module' object has no attribute 'filedialog'

I understand that I have to import tkinter.filedialog to make this work in shell.

Why the difference between IDLE and shell? How can I make IDLE act like shell? It can be frustrating to have a script working in IDLE, and failing in shell.

I am using Python 3.4.

Sure answered 6/8, 2016 at 16:57 Comment(3)
Possible duplicate of Tkinter code using font module can't run from command line?Nudnik
@TerryJanReedy Yes, that post describes a similar problem. Shouldn't the script environment be isolated from whatever the IDLE uses for its own needs? And also, if I type tkinter or tk in IDLE, it says name 'tkinter' is not defined or name 'tk' is not defined, which it should be defined if the explanation in that other post is correct.Sure
I retracted the close request because you asked not 'why', which you figured out, but 'how to fix'. I answered that below. And yes, the script environment should be isolated as much as possible. This is the reason to execute code in a separate process. The IDLE doc has a section 3.2. IDLE - console differences that list some that are inevitable. I am still working to reduce the number of extra modules in sys.modules to a minimum. (bugs.python.org/issue27534). The current reduction reduces import time in run.py by 45% for me.Nudnik
N
1

This is an IDLE bug which I fixed for future 3.5.3 and 3.6.0a4 releases. Tracker issue.

For an existing 3.5 or 3.4 release, add the following to idlelib/run.py just before the LOCALHOST line.

for mod in ('simpledialog', 'messagebox', 'font',
            'dialog', 'filedialog', 'commondialog',
            'colorchooser'):
    delattr(tkinter, mod)
    del sys.modules['tkinter.' + mod]

I presume that this will work with earlier 3.x releases, but do not have them installed to test. For existing 3.6.0a_ releases, replace 'colorchooser' with 'ttk'.

Nudnik answered 6/8, 2016 at 20:28 Comment(2)
Terry, thank you for maintaining the IDLE. I really like the idea of an IDE being packaged with a programming language. This makes it easy to deploy on machines you rarely work on. Have you had any luck finding a solution for the CPU usage that I asked in #32551905 ? I still can't figure out what is the pattern that triggers it, it doesn't happen all the time.Sure
Thanks for the positive feedback.Nudnik

© 2022 - 2024 — McMap. All rights reserved.