[tkinter] importing tkinter and ttk into 1 namespace

Post here if you need help with creating a Graphical User Interface in Python.

[tkinter] importing tkinter and ttk into 1 namespace

Postby hrs » Sat Jun 22, 2013 12:02 pm

It's not a good idea to dump all of a modules content into the global namespace like this:
Code: Select all
from tkinter import *

because you may overwrite previously imported stuff. However, ttk has the feature that it allows you to overwrite part of tkinter with drop-in replacement widgets:
Code: Select all
from tkinter import *
from tkinter.ttk import *


Now if I try to put it into a namespace called tk:
Code: Select all
import tkinter as tk
import tkinter.ttk as tk

I end up with a namespace tk containing only tkinter.ttk. I.e. import tkinter as tk is destroyed.

How can you import tkinter the right way and use the overwriting feature of ttk?

The above asumes python3.
hrs
 
Posts: 86
Joined: Thu Feb 07, 2013 9:26 pm

Re: [tkinter] importing tkinter and ttk into 1 namespace

Postby Yoriz » Sat Jun 22, 2013 12:15 pm

Looking at the ttk module it imports tkinter so you should be able to have your import as
Code: Select all
import tkinter.ttk as tk

and when you want something that is from tkinter
Code: Select all
tk.tkinter.whater_you_normally_use_here

so this should give you a ttk button
Code: Select all
tk.Button

and this should give a tkinter button
Code: Select all
tk.tkinter.Button
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 759
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: [tkinter] importing tkinter and ttk into 1 namespace

Postby hrs » Sat Jun 22, 2013 1:33 pm

Looking at the ttk module it imports tkinter

I was unaware of that, thanks.

Though it doesn't accomplish ttk overwriting tkinter widgets. The point of this would be that you can take old code without modifying it and all you need to do is add an import statement to get themed widgets (making tkinter look much better!).
hrs
 
Posts: 86
Joined: Thu Feb 07, 2013 9:26 pm

Re: [tkinter] importing tkinter and ttk into 1 namespace

Postby Yoriz » Sat Jun 22, 2013 2:04 pm

Try this
Code: Select all
import tkinter as tk
import tkinter.ttk as ttk

[setattr(tk, name, getattr(ttk, name)) for name in ttk.__all__]
New Users, Read This
Join the #python-forum IRC channel on irc.freenode.net!
Spam topic disapproval technician
Windows7, Python 2.7.4., WxPython 2.9.5.0., some Python 3.3
User avatar
Yoriz
 
Posts: 759
Joined: Fri Feb 08, 2013 1:35 am
Location: UK

Re: [tkinter] importing tkinter and ttk into 1 namespace

Postby hrs » Sat Jun 22, 2013 9:44 pm

I'll give that a try. Thanks Yoriz.
hrs
 
Posts: 86
Joined: Thu Feb 07, 2013 9:26 pm


Return to GUI

Who is online

Users browsing this forum: No registered users and 2 guests

cron