Friday, July 3, 2015

Python: Tkinter GUI (3)

Abstract: how to import Tkinter ?

  One lazy way of importing Tkinter in Python is ‘from Tkinter import *’. All classed in Tkinter will be in your main namespace. But that is considered harmful because it may cause name collisions in the main namespace. For example:
  This script runs well
from Tkinter import *
msg = Message(text="import Tkinter?")
msg.config(bg='pink', font=('times', 16, 'italic'))
msg.pack()
mainloop()

  But This script would return an error:
from Tkinter import *
from tkMessageBox import *
msg = Message(text="
import Tkinter?")
msg.config(bg='pink', font=('times', 16, 'italic'))
msg.pack()
mainloop()


AttributeError: Message instance has no attribute “pack”.

Here, the Message class is used. There are two Message classed in Tkinter.Message and tkMessageBox.Message. But no pack() method in the later class. Therefore there is an error. Hence, a better way to import Tkinter is :
import Tkinter as Tk
import tkMessageBox as tkMB
msg = Tk.Message(text="
import Tkinter?")
msg.config(bg='pink', font=('times', 16, 'italic'))
msg.pack()
mainloop()



Writing date: 20150703

No comments:

Post a Comment