Saturday, July 21, 2012

Tkinter Labels with Unicode

This demo is based on the Tcl unicodeout.tcl demo.



# File: unicodeout.py

from tkinter import *
from tkinter import ttk
from demopanels import MsgPanel, SeeDismissPanel

class UnicodeLabelDemo(ttk.Frame):

    def __init__(self, isapp=True, name='labeldemo'):
        ttk.Frame.__init__(self, name=name)
        self.pack(expand=Y, fill=BOTH)  # resizeable
        self.master.title('Label with Unicode Demo')
        self.isapp = isapp
        self._create_widgets()

    def _create_widgets(self):
        if self.isapp:
            MsgPanel(self, 
                     ["This is a sample of Tk's support for languages that uses ",
                      "non-Western character sets.  However, what you will actually see ",
                      "below depends largely on the character sets you have installed; ",
                      "and what you see for characters that are not present varies greatly ",
                      "between platforms as well.  The strings are written as ",
                      "UNICODE escaped characters ( \\uXXXX ), making them portable."])
            
            SeeDismissPanel(self)
        
        self._create_demo_panel()
            
    def _create_demo_panel(self):
        demoPanel = Frame(self)
        demoPanel.pack(expand=Y, fill=BOTH, padx=25)
    
        row = 0
        for k,v in sorted(SAMPLES.items()):
            # anchor keeps text left aligned in grid cell
            Label(text=k, anchor=NW).grid(in_=demoPanel, sticky=EW, 
                                          pady=0, row=row, column=0)
            Label(text=v, anchor=NW, 
                  font=("Helvitica", 12, 'italic')).grid(in_=demoPanel, sticky=EW,
                                                         pady=0, 
                                                         row=row, column= 1)
            row += 1
           
        demoPanel.columnconfigure(1, weight=1)
        
# sample language strings
SAMPLES = {"Arabic": "\u0627\u0644\u0643\u0644\u0645\u0629 " \
                     "\u0627\u0644\u0639\u0631\u0628\u064A\u0629",
           "Trad. Chinese": "\u4E2D\u570B\u7684\u6F22\u5B57",
           "Simp. Chinese": "\u6C49\u8BED",
           "Greek": "\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AE " \
                    "\u03B3\u03BB\u03CE\u03C3\u03C3\u03B1",
           "Hebrew": "\u05DB\u05EA\u05D1\u05E2\u05D1\u05E8\u05D9\u05EA",
           "Japanese": "\u65E5\u672C\u8A9E\u306E\u3072\u3089\u304C\u306A, " \
                       "\u6F22\u5B57\u3068\u30AB\u30BF\u30AB\u30CA",
           "Korean": "\uB300\uD55C\uBBFC\uAD6D\uC758 \uD55C\uAE00",
           "Russian": "\u0420\u0443\u0441\u0441\u043A\u0438\u0439 \u044F\u0437\u044B\u043A"
        }


if __name__ == '__main__':
    UnicodeLabelDemo().mainloop()