[Tutor] Tkinter layout question

Peter Otten __peter__ at web.de
Sat Apr 22 04:37:19 EDT 2017


Phil wrote:

> On Thu, 20 Apr 2017 13:43:07 +0100
> Alan Gauld via Tutor <tutor at python.org> wrote:
> 
>> If still confused drop a question here.
> 
> Maybe not totally confused, more a question of best practice.
> 
> Using your example table class, I commented out all from, and including,
> "if __name__ == "__main__":" down and saved the file as table_class.py. 

That's unnecessary. The code protected by 'if __name__ == "__main__"' is not 
executed when the module is imported. In fact that's the very purpose of 
this idiom.

> I
> then created test.py as follows:
> 
> from table_class import *

"Best practice" is to avoid star imports which bind every name from 
table_class that does not start with "_", including 'tk' to the same name in 
the importing module.

Instead be explicit:

import tkinter as tk
import table_class

...

tab = table_class.DisplayTable(...)

That way the maintainer of table_class.py only has to be careful to keep 
DisplayTable compatible. A change to the import from

import tkinter as tk

to

import tkinter

or the definition of names that collide with names in other modules leaves 
client code unaffected.

> top = tk.Tk()
> 
> tab = DisplayTable(top,
>                     ["Left","middle","Right"],
>                     [[1,2,1],
>                     [3,4,3],
>                     [5,6,5]],
>                     datacolor='blue',
>                     cellcolor='yellow',
>                     gridcolor='red',
>                     hdcolor='black')
> 
> tab.pack()
> 
> Two questions:
> I can see where tk comes from but I'm unsure of the origin of Tk() other
> than a reference to tkinter. Have I used you table class correctly? It
> works, of course, but it doesn't look correct.
> 




More information about the Tutor mailing list