A little import confusion with tkinter

So I am a little confused on the importing of modules in python, specifically in regards to tkinter. In this small code snippet for a hello world app

from tkinter import *
from tkinter import ttk
root = Tk()
frm = ttk.Frame(root, padding=10)
frm.grid()
ttk.Label(frm, text=“Hello World!”).grid(column=0, row=0)
ttk.Button(frm, text=“Quit”, command=root.destroy).grid(column=1, row=0)
root.mainloop()

I do not understand why you need both import statements, wouldn’t ‘from tkinter import *’ import all references to tkinter, why the need for the second import. Also, to use a tkinter messagebox, I would also need ‘from tkinter import messagebox’, why? And lastly , shouldn’t just ‘import tkinter’ also import all references? Obviously i am a bit confused on the whole import function. Any help would be greatly appreciated.

Submodules aren’t imported from a parent module import (whether via * or just by importing the parent). You can make various things happen by tweaking the init file for the module, but by default they are not imported.

1 Like

Hi and welcome.

A couple of things to note here:

  1. When posting code blocks, please use markdown
```python
<my code>
```

… where <my code> is the code block that you’ve constructed.

  1. import* is discouraged because it brings a lot of variables (many of which you may not need) into your namespace.
    Remember: Explicit is better than implicit.

As @BowlOfRed correctly says, you only get the objects and functions from the stated module: if you need a ‘sub-module’, then you need to be specific – from module import sub_module

By BowlOfRed via Discussions on Python.org at 22Jul2022 20:13:

Submodules aren’t imported from a parent module import (whether via *
or just by importing the parent). You can make various things happen
by tweaking the init file for the module, but by default they are not
imported.

There’s more detailed discussion here, too:

Cheers,
Cameron Simpson cs@cskk.id.au