-4

I am writing a python GUI script and I have a problem with the import/from.

I find the I can not delete one of the lines above as the script will not work. Therefore, why and is there a way to make this shorter?

script:

import tkinter
import tkinter.messagebox
from tkinter import *
from tkinter.filedialog import  asksaveasfilename, askdirectory
from tkinter import ttk
...
lroca
  • 621
  • 2
  • 8
  • 19
  • I recommend reading the [documentation on using modules](https://docs.python.org/3.4/tutorial/modules.html). – TigerhawkT3 Jul 17 '15 at 18:07
  • Where did you get the idea that making code shorter by removing working lines makes it better?! – Two-Bit Alchemist Jul 17 '15 at 18:07
  • Well, `import tkinter` and `from tkinter import *` aren't both necessary unless the code uses both `button = Button(root)` and `label = tkinter.Label(root)`, which it shouldn't, but sounds like it does. – TigerhawkT3 Jul 17 '15 at 18:09

1 Answers1

1

When you do import tkinter, then you must prefix all tkinter commands and constants with tkinter. (eg: buttontkinter.Button(...), root=tkinter.Tk(), etc).

When you do from tkinter import *, it imports everything that tkinter has marked as exportable, and you do not prefix things with tkinter. (eg: button=Button(...), root=Tk(), etc)

You should do one or the other, not both. Preferably, do the former. To make for a little less typing you can import with an alias, for example:

import tkinter as tk
...
root = tk.Tk()
button = tk.Button(root, ...)

Note that this isn't a tkinter-specific problem. This is fundamentally how importing all modules in python works.

Also note that, while ttk is in tkinter, it doesn't get imported when you do from tkinter import *. Also, ttk will export classes with the same name as tkinter (for example: they both define Button)

For more information, read the documentation on modules in the python documentation. You might also want to read the answers to ImportError when importing Tkinter in Python

Community
  • 1
  • 1
Bryan Oakley
  • 370,779
  • 53
  • 539
  • 685