Пример #1
2
	def text(self, output, pos, anchor=tk.NW, justify='left',
		font='Arial', size=12, decoration='', shadow=True, split=False):
		# http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/create_text.html
		# http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/fonts.html
		#size = util.grep('[1-9]?[0-9]{1,2}', font, n=0)
		# choose font
		fid='{} {} {}'.format(font, size, decoration)
		f = fonts.get(fid)
		if not f:
			w = ['normal', 'bold'][decoration.count('bold')>0]
			s = ['roman', 'italic'][decoration.count('italic')>0]
			u = int(decoration.count('underline')>0)
			f = Font(family=font, size=-size, weight=w,
				slant=s, underline=u)
			fonts[fid]=f
		# start aligning output
		x, y = pos
		for xx,yy in [(0,1),(1,0),(0,-1),(-1,0),(1,1),(2,0)]:
			self.cnv.create_text(x+xx, y+yy, anchor=anchor,
				font=f,
				justify=justify,
				fill='black',
				text=output)
		self.cnv.create_text(x, y, anchor=anchor,
			font=f,
			justify=justify,
			fill='white',
			text=output)
		return x+f.measure(output), y+len(output.split('\n'))*size
	def fillInUI(self, parent):
		label = Tk.Label(parent,
			text="Warning: clipping is turned on (see Side View"
			" tool) and will severely slow down POV-Ray raytracing.",
			justify='left', height=2)
		import tkFont
		font = tkFont.Font(root=parent, font=label.cget('font'))
		label.config(wraplength=(self.text_width * font.measure('n')))
		label.grid(row=0, columnspan=2, sticky=Tk.W, pady=5)

		off = Tk.Button(parent, text="Turn off clipping",
				command=self.__turnOff)
		off.grid(row=1, column=0, pady=1)

		if ClipWarning.__dsVar is None:
			ClipWarning.__dsVar = Tk.IntVar(chimera.tkgui.app)
			ClipWarning.__dsVar.set(False)
		ds = Tk.Checkbutton(parent, variable=ClipWarning.__dsVar,
			text="Don't show dialog again")
		from tkFont import Font
		font = Font(font=ds.cget('font'))
		font.config(size=int(0.75*float(font.cget('size'))+0.5),
					weight='normal')
		ds.config(font=font)
		ds.grid(row=1, column=1, sticky=Tk.SE, pady=1)

		parent.rowconfigure(0, weight=1)
		parent.columnconfigure(0, weight=1)
    def GetFont(self, root, configType, section):
        """Retrieve a font from configuration (font, font-size, font-bold)
        Intercept the special value 'TkFixedFont' and substitute
        the actual font, factoring in some tweaks if needed for
        appearance sakes.

        The 'root' parameter can normally be any valid Tkinter widget.

        Return a tuple (family, size, weight) suitable for passing
        to tkinter.Font
        """
        family = self.GetOption(configType, section, 'font', default='courier')
        size = self.GetOption(configType, section, 'font-size', type='int',
                              default='10')
        bold = self.GetOption(configType, section, 'font-bold', default=0,
                              type='bool')
        if (family == 'TkFixedFont'):
            if TkVersion < 8.5:
                family = 'Courier'
            else:
                f = Font(name='TkFixedFont', exists=True, root=root)
                actualFont = Font.actual(f)
                family = actualFont['family']
                size = actualFont['size']
                if size <= 0:
                    size = 10  # if font in pixels, ignore actual size
                bold = actualFont['weight']=='bold'
        return (family, size, 'bold' if bold else 'normal')
Пример #4
0
    def __init__(self, parent, controller, frames):
        self.parent = parent
        self.controller = controller

        title_font = Font(family='Helvetica',
                          size=15,
                          weight="bold",
                          slant="italic")
        Label(self.parent, text='Summary', font=title_font).pack(side="top",
                                                                 fill="x",
                                                                 pady=10)

        self.widths = [18, 40, 60]

        self.frame = Frame(self.parent)
        self.frame.pack()
        font = Font(weight="bold", slant="italic")  # family='Helvetica',

        for col, txt in enumerate(["Section", "Parameters", "cmd"]):
            Label(self.frame,
                  text=txt,
                  relief=RIDGE,
                  width=int(self.widths[col]),
                  height=3,
                  font=font).grid(row=0, column=col)

        curr_row = 1
        for F in frames:
            num_rows = self.get_summary(curr_row, F.get_data(), F.title,
                                        F.get_cmd())
            curr_row += num_rows

        Button(self.parent, text="Exit",
               command=self.parent.destroy).pack(side=BOTTOM)
Пример #5
0
	def __init__(self,parent,frames=None,aligns=None,weights=None,**kwargs):
		Frame.__init__(self,parent,**kwargs)
		self.numberOfRows=0
		self.aligns = aligns
		if not self.aligns:
			self.aligns = ["left","left","left","left","left","left"]
		if not weights:
			weights=[1,1,1,1]
		if frames==None:
			self.frames=["one","two","three","four","five","six"]
		else:
			self.frames=frames
		# for i in range(0,len(self.frames)):
		# 	self.frames[i]=Frame(self)
		# 	self.frames[i].grid(side=LEFT,expand=1,fill=BOTH)

		self.textBoxes=[]
		for i in range(0,len(self.frames)):
			self.textBoxes.append(Text(self,bd=0,width=0,state='disabled'))
			self.textBoxes[-1].grid(row=0,column=i,sticky=W+E+N+S)
			self.textBoxes[-1].tag_configure("right",justify="right",wrap=NONE)
			self.textBoxes[-1].tag_configure("center",justify="center",wrap=NONE)
			self.textBoxes[-1].tag_configure("left",justify="left",wrap=NONE)
			self.textBoxes[-1].tag_configure("underline",underline=True)
			self.grid_columnconfigure(i,weight=weights[i])
		self.grid_rowconfigure(0,weight=1)
		self.boldFont = Font(self.textBoxes[0],self.textBoxes[0].cget('font'))
		self.boldFont.configure(weight='bold')
		for i in self.textBoxes:
			i.tag_configure("bold",font=self.boldFont)
Пример #6
0
 def calculate_text_width(text,
                          family=TREEVIEW_FONT_NAME,
                          size=TREEVIEW_FONT_SIZE):
     # create the font
     font = Font(family=family, size=size)
     # measure the width of the text and return
     return font.measure(text)
Пример #7
0
 def __init__(self, master, title, text):
     Toplevel.__init__(self, master=master)
     self.title(title)
     fra = Frame(self)
     fra.grid(row=0, column=0, pady=5, padx=5)
     self.tx = Text(fra, width=130, height=20, wrap=WORD)
     scr = Scrollbar(fra, command=self.tx.yview)
     self.tx.configure(yscrollcommand=scr.set)
     self.tx.pack(side=LEFT)
     scr.pack(side=RIGHT, fill=Y)
     self.tx.bind('<Enter>',
                  lambda e: self._bound_to_mousewheel(e, self.tx))
     self.tx.bind('<Leave>', self._unbound_to_mousewheel)
     self.tx.insert(END, text)
     self.tx.configure(state='disabled')
     if platform == "darwin":
         button_font = Font(family='Arial', size=15)
     else:
         button_font = Font(font=Button()["font"])
     closeTopolPrevB = Button(self,
                              text='Exit',
                              bg='red',
                              command=self.destroy,
                              font=button_font)
     closeTopolPrevB.grid(row=1, column=0, pady=5)
Пример #8
0
def add_assembly():
    """添加组件"""
    init()

    buy_house_static = Label(master, text=u'购房: ', font=Font(size=15))
    buy_house_static.place(anchor=u'nw', x=440, y=50)
    buy_car_static = Label(master, text=u'购车: ', font=Font(size=15))
    buy_car_static.place(anchor=u'nw', x=440, y=75)
    age_static = Label(master, text=u'年龄: ', font=Font(size=15))
    age_static.place(anchor=u'nw', x=440, y=100)
    height_static = Label(master, text=u'身高: ', font=Font(size=15))
    height_static.place(anchor=u'nw', x=440, y=125)
    salary_static = Label(master, text=u'工资: ', font=Font(size=15))
    salary_static.place(anchor=u'nw', x=440, y=150)
    education_static = Label(master, text=u'学历: ', font=Font(size=15))
    education_static.place(anchor=u'nw', x=440, y=175)
    company_static = Label(master, text=u'公司: ', font=Font(size=15))
    company_static.place(anchor=u'nw', x=440, y=200)
    industry_static = Label(master, text=u'行业: ', font=Font(size=15))
    industry_static.place(anchor=u'nw', x=440, y=225)
    school_static = Label(master, text=u'学校: ', font=Font(size=15))
    school_static.place(anchor=u'nw', x=440, y=250)
    position_static = Label(master, text=u'职位: ', font=Font(size=15))
    position_static.place(anchor=u'nw', x=440, y=275)
    previous = Button(master, text=u'上一个', command=handle_previous)
    previous.place(anchor=u'nw', x=10, y=490)
    next = Button(master, text=u'下一个', command=handle_next)
    next.place(anchor=u'nw', x=520, y=490)
Пример #9
0
 def _tk_redraw_canvas(self, width, height):
     if self._canvas:
         self._canvas.destroy()
     self._fnormal = Font(family='Monospace', size=13)
     self._fbold = Font(family='Monospace', weight='bold', size=13)
     self._fitalic = Font(family='Monospace', slant='italic', size=13)
     self._fbolditalic = Font(family='Monospace',
                              weight='bold',
                              slant='italic',
                              size=13)
     self._colsize = self._fnormal.measure('A')
     self._rowsize = self._fnormal.metrics('linespace')
     self._canvas = Canvas(self._root,
                           width=self._colsize * width,
                           height=self._rowsize * height)
     self._tk_fill_region(0, height - 1, 0, width - 1)
     self._cursor_row = 0
     self._cursor_col = 0
     self._scroll_top = 0
     self._scroll_bot = height - 1
     self._scroll_left = 0
     self._scroll_right = width - 1
     self._width, self._height = (
         width,
         height,
     )
     self._canvas.pack()
Пример #10
0
class TkFont():
    def __init__(self,
                 family="Calibri",
                 weight=NORMAL,
                 slant=ROMAN,
                 overstrike=0,
                 underline=0,
                 size=12):
        '''
        family: 字符集
        size: 字体大小
        weight: "bold" for boldface, "normal" for regular weight.        
        slant: "italic" for italic, "roman" for unslanted.        
        underline: 1 for underlined text, 0 for normal.
        overstrike: 1 for overstruck text, 0 for normal.
        '''
        self.font = Font(family=family,
                         weight=weight,
                         slant=slant,
                         overstrike=overstrike,
                         underline=underline,
                         size=size)

    def get_actual_font_info(self):
        return self.font.actual()

    def config(self, **kw):
        self.font.config(**kw)
Пример #11
0
    def __init__(self,
                 master=None,
                 startLatch=None,
                 stopLatch=None,
                 ghostXfer=None):
        tk.Frame.__init__(self, master, width=1024, height=600)
        self.pack(fill=None, expand=False)

        self.zones = {}
        self.buttonfont = Font(family="ledfixed", size=30)
        self.statusfont = Font(family="ledfixed", size=20)
        self.megafont = Font(family="ledfixed", size=150, weight="bold")
        self.timer = tk.StringVar()
        self.timer.set("--.-")
        self.bmatest = 2

        self.currentStatus = tk.StringVar()
        self.ghost = None

        # Be sure to define these after instantiating the class
        self.startLatch = startLatch
        self.stopLatch = stopLatch
        self.ghostXfer = ghostXfer

        self.createLayout()
        self.refresh_filepicker()
Пример #12
0
 def __init__(self, wdw, sols):
     """
     Stores the list of solutions in sols
     and defines the layout of the GUI.
     """
     wdw.title('solutions scroller')
     self.sols = sols
     self.cursor = 0
     self.lbl = Label(wdw, text="solution : ")
     self.lbl.grid(row=0, column=0, sticky=E)
     self.ent = Entry(wdw)
     self.ent.grid(row=0, column=1, stick=W)
     self.ent.insert(INSERT, "0 of %d" % len(sols))
     self.myft = Font(family="Courier New", size=12, weight="normal")
     self.mlen = self.myft.measure("M")
     lines = sols[0].split('\n')
     self.width = max([len(line) for line in lines])
     self.display = StringVar()
     self.display.set(self.sols[0])
     self.mess = Message(wdw, textvariable=self.display, \
         font=self.myft, width=self.width*self.mlen, background='white')
     self.mess.grid(row=1, column=0, columnspan=2)
     self.btnext = Button(wdw, command=self.next, text='next')
     self.btnext.grid(row=2, column=1, sticky=W + E)
     self.btprev = Button(wdw, command=self.previous, text='previous')
     self.btprev.grid(row=2, column=0, sticky=W + E)
Пример #13
0
 def __init__(self, parent):
     tk.Frame.__init__(self, parent)
     self.parent = parent
     self.custom_font = Font(family='Times', size=17)
     self.label_font = Font(family='URW Chancery L', size=16)
     self.default_font = Font(family='Century Schoolbook L', size=17)
     self.style = ttk.Style()
     self.initialize()
Пример #14
0
 def findfont(self, faces, sz=11, boldflg=False, italicflg=False):
     for face in faces:
         font = Font(root=self.root,
                     family=face,
                     size=sz,
                     weight = 'bold' if boldflg else 'normal',
                     slant = 'italic' if italicflg else 'roman')
         if face == font.actual('family'):
             return font
Пример #15
0
 def underline_command(self,*args):
     current_tags = self.textPad.tag_names()
     underline = Font(self.textPad, self.textPad.cget("font"))
     underline.config(underline=True)
     self.textPad.tag_config("und", font=underline)
     if "und" in current_tags:
             self.textPad.tag_delete("und", '1.0', 'end-1c')
     else:
             self.textPad.tag_add("und", '1.0', 'end-1c')
Пример #16
0
 def findfont(self, faces, sz=11, boldflg=False, italicflg=False):
     for face in faces:
         font = Font(root=self.root,
                     family=face,
                     size=sz,
                     weight='bold' if boldflg else 'normal',
                     slant='italic' if italicflg else 'roman')
         if face == font.actual('family'):
             return font
Пример #17
0
 def italic_command(self,*args):
     current_tags = self.textPad.tag_names()
     italics = Font(self.textPad, self.textPad.cget("font"))
     italics.config(slant="italic")
     self.textPad.tag_config("ita", font=italics)
     if "ita" in current_tags:
             self.textPad.tag_delete("ita", '1.0', 'end-1c')
     else:
             self.textPad.tag_add("ita", '1.0', 'end-1c')
Пример #18
0
 def bolditalic_command(self,*args):
     current_tags = self.textPad.tag_names()
     bold_italic = Font(self.textPad, self.textPad.cget("font"))
     bold_italic.config(weight="bold",slant="italic")
     self.textPad.tag_config("bldita", font=bold_italic)
     if "bldita" in current_tags:
             self.textPad.tag_delete("bldita", '1.0', 'end-1c')
     else:
             self.textPad.tag_add("bldita", '1.0', 'end-1c')
Пример #19
0
 def font_command(self,*args):
     try:
             font_specs = askstring("Font", "Font Style-Font Size")
             font_specs = font_specs.split('-')
             new_font = Font(self.textPad, self.textPad.cget("font"))
             new_font.config(family=font_specs[0], size=font_specs[1])
             self.textPad.tag_config("newfont", font=new_font)
             self.textPad.tag_add("newfont", '1.0', 'end-1c')
     except:
             pass
Пример #20
0
 def italic(self, *args):  # Works only if text is selected
     try:
         current_tags = self.text.tag_names("sel.first")
         if "italic" in current_tags:
             self.text.tag_remove("italic", "sel.first", "sel.last")
         else:
             self.text.tag_add("italic", "sel.first", "sel.last")
             italic_font = Font(self.text, self.text.cget("font"))
             italic_font.configure(slant="italic")
             self.text.tag_configure("italic", font=italic_font)
     except:
         pass
Пример #21
0
 def set_font(self, fontdesc):
     self.text.config(font=fontdesc)
     normal_font = Font(self.text, self.text.cget('font'))
     self.bold_font = bold_font = Font(self.text, self.text.cget('font'))
     self.bold_font.config(weight='bold')
     self.char_size = normal_font.measure('M')
     text = self.text
     text.tag_config('output', font=normal_font)
     text.tag_config('Prompt', foreground='#0000cc', font=normal_font)
     text.tag_config('PromptNum', foreground='#0000bb', font=bold_font)
     text.tag_config('OutPrompt', foreground='#cc0000', font=normal_font)
     text.tag_config('OutPromptNum', foreground='#bb0000', font=bold_font)
Пример #22
0
 def overstrike(self, *args):  # Works only if text is selected
     try:
         current_tags = self.text.tag_names("sel.first")
         if "overstrike" in current_tags:
             self.text.tag_remove("overstrike", "sel.first", "sel.last")
         else:
             self.text.tag_add("overstrike", "sel.first", "sel.last")
             overstrike_font = Font(self.text, self.text.cget("font"))
             overstrike_font.configure(overstrike=1)
             self.text.tag_configure("overstrike", font=overstrike_font)
     except:
         pass
Пример #23
0
 def underline(self, *args):  # Works only if text is selected
     try:
         current_tags = self.text.tag_names("sel.first")
         if "underline" in current_tags:
             self.text.tag_remove("underline", "sel.first", "sel.last")
         else:
             self.text.tag_add("underline", "sel.first", "sel.last")
             underline_font = Font(self.text, self.text.cget("font"))
             underline_font.configure(underline=1)
             self.text.tag_configure("underline", font=underline_font)
     except:
         pass
Пример #24
0
 def bold(self, *args):  # Works only if text is selected
     try:
         current_tags = self.text.tag_names("sel.first")
         if "bold" in current_tags:
             self.text.tag_remove("bold", "sel.first", "sel.last")
         else:
             self.text.tag_add("bold", "sel.first", "sel.last")
             bold_font = Font(self.text, self.text.cget("font"))
             bold_font.configure(weight="bold")
             self.text.tag_configure("bold", font=bold_font)
     except:
         pass
Пример #25
0
    def open(self):
        if self.is_open == False:
            self.window = Toplevel(self.parent)
        self.window.geometry("370x380+" + str(self.parent.control_panel_xpos) + "+" + str(self.parent.control_panel_ypos))  
        self.window.wm_title("CK control panel")
        self.window.configure(bg="black")
        print("loading control window")
        self.window.protocol('WM_DELETE_WINDOW', self.cp_close)
        self.pgm_box = []
        self.pgm_down = []
        self.pgm_up = []
        self.inst_button = []
        self.k1 = []
        self.k2 = []
        self.fish = []
        self.fishman_strings = ['All','E','A','D','G','B','e']
        
        self.font_big = Font(family="Ariel", size=24)
        self.font_med = Font(family="Ariel", size=18)

        self.button_play = Button(self.window, text="Play", command=lambda: self.parent.q(self.parent.ls.playback(['play'])),bg="#003366", fg="white", width=5)
        self.button_play.grid(row=5, column=1)
        self.button_stop = Button(self.window, text="Stop", command=lambda: self.parent.q(self.parent.ls.playback(['stop'])),bg="#003366", fg="white", width=5)
        self.button_stop.grid(row=5, column=2)
        
        #self.sv = StringVar()
        #self.sv.trace("w", lambda name, index, mode, sv=self.sv: self.text_changed())
        
        self.loops_button = Button(self.window, text="Loops", command=lambda: self.parent.q(self.parent.ls.select(["Loops",1])),bg="#003366", fg="white", width=5)
        self.loops_button.grid(row=1, column=7)
        
        row_offset = 2
        for i,instrument in enumerate(['Kontakt','GuitarIn','Massive','FM8']):
            print ("br",i,instrument)
            self.inst_button.append(Button(self.window, text=instrument, command=lambda l_inst = instrument: self.parent.q(self.parent.ls.select([l_inst])),bg="#003366", fg="white", width=len(instrument)))
            self.inst_button[i].grid(row=i+row_offset, column=7)
            self.pgm_up.append(Button(self.window, text="Next\nPgm", command=lambda li = i: self.program_button(li,1),bg="#003366", fg="white", width=5))
            self.pgm_up[i].grid(row=i+row_offset, column=6)
            self.pgm_box.append(Entry(self.window, width=3,exportselection=False, bg="black", fg="lightblue", font=self.font_big, insertbackground="white")) #, textvariable = self.sv, borderwidth=0) 
            self.pgm_box[i].grid(row=i+row_offset, column=5,sticky=W)
            self.pgm_box[i].insert(0,"1")
            self.pgm_down.append(Button(self.window, text="Prev\nPgm", command=lambda li = i: self.program_button(li,-1),bg="#003366", fg="white", width=5))
            self.pgm_down[i].grid(row=i+row_offset, column=4)
            self.k2.append(Button(self.window, text="K2", command=lambda l_inst = instrument: self.parent.q(self.parent.ls.output(['KeysIn2',l_inst])),bg="#003366", fg="white", width=5))
            self.k2[i].grid(row=i+row_offset, column=3)
            self.k1.append(Button(self.window, text="K1", command=lambda l_inst = instrument: self.parent.q(self.parent.ls.output(['KeysIn1',l_inst])),bg="#003366", fg="white", width=5))
            self.k1[i].grid(row=i+row_offset, column=2)
            self.fish.append(Button(self.window, text="Fish", command=lambda l_inst = instrument: self.parent.q(self.parent.ls.output(['Fishman',l_inst])),bg="#003366", fg="white", width=5))
            self.fish[i].grid(row=i+row_offset, column=1)
 

        self.window.focus_set()
Пример #26
0
 def __init__(self, text, regexp=False, nocase=False):
     self.text = text
     self.pattern = tkinter.StringVar()
     self.regexp = tkinter.IntVar(int(regexp))
     self.nocase = tkinter.IntVar(int(nocase))
     self.prev_pattern = ""
     self.prev_regexp = regexp
     self.prev_nocase = nocase
     self.findings = []
     self.current = -1
     self.text.tag_config("search", background='yellow', foreground="black")
     bold_font = Font(self.text)
     bold_font.configure(weight="bold")
     self.text.tag_config("search_current", font=bold_font)
Пример #27
0
	def __init__(self, parent):
		Tkinter.Frame.__init__(self, parent)
		self.menu = Pmw.OptionMenu(self, items=self.ambiguity,
			label_text="Ambiguity codes:", labelpos='w',
			command=self._configureInfo)
		self.menu.grid(row=0)

		self.label = Tkinter.Label(self, bd=0, padx=0, pady=0)
		from tkFont import Font
		font = Font(font=self.label.cget('font'))
		font.config(size=int(0.75*float(font.cget('size'))+0.5),
							weight="normal")
		self.label.config(font=font)
		self.label.grid(row=1)
        def __init__(self):
                super(Tkinter, self).__init__()

                #Inicialitzem la finestra emb les mides i el titol
                self.app1 = Tk()
                self.app1.title("Control del consum electric")
                self.app1.geometry("800x450")
                self.fondo = PhotoImage(file="fondo.gif")
                self.lbl_Fondo = Label(self.app1, image=self.fondo).place(x=0,y=0)

                #Importem les classes dels altres arxius
                self.database = Database()
                self.sensor = PowerServer()

                #TIpus i mides de lletres que utilitzarem
                self.myFont = Font(family="Verdana", size=16)
                self.myFont2 = Font(family="Verdana",weight="bold", size=20)
                self.myFont3 = Font(family="Verdana",weight="bold", size=26)
                self.myFont4 = Font(family="Verdana", size=12, weight="bold")

                #Definim les variables de lectura i la seva estructura
                self.sensor1 = StringVar()
                self.sensor2 = StringVar()
                self.sensor3 = StringVar()
                self.sensor1.set("- - "+" W")
                self.sensor2.set("- -"+" W")
                self.sensor3.set("- -"+" W")

                #Insertem el text de les instruccions a seguir
                lbl = Label(self.app1,text=" Instruccions d'us:"
                            "\n\n  - Primer de tot assegura't\n"
                            " de tenir conectades les pinces que utilitzaras.\n"
                            "  A la part superior de les pinces hi ha un fletxa\n"
                            " que s'ha de col·locar en direcció de la corrent\n"
                            "  - Si disposes de connexió a internet configura-la\n"
                            " a la part superior de l'esquerra de la pantalla",
                             justify=LEFT, font=self.myFont,bg="khaki",
                             highlightbackground="gold3", highlightthickness=3, padx=10, )
                lbl.place(x=150,y=100)

                #Boto per continuar despres de llegir les instruccions
                button_continuar = Button(self.app1,text="Continuar",font=self.myFont,command=self.tipus_instalacio,
                              bg="khaki", bd=3, activebackground="gold",relief=RIDGE, overrelief=GROOVE,
                              highlightbackground="gold3", highlightthickness=3 )
                button_continuar.place(x=350,y=350)


                self.app1.mainloop()
Пример #29
0
def main(root, text, menubar):
    objFormat = Format(text)

    fontoptions = families(root)
    font = Font(family="Verdana", size=10)

    formatMenu = Menu(menubar)

    fsubmenu = Menu(formatMenu, tearoff=0)
    ssubmenu = Menu(formatMenu, tearoff=0)

    for option in fontoptions:
        fsubmenu.add_command(label=option,
                             command=lambda: font.configure(family=option))
    for value in range(1, 31):
        ssubmenu.add_command(label=str(value),
                             command=lambda: font.configure(size=value))

    formatMenu.add_command(label="Change Background",
                           command=objFormat.changeBg)
    formatMenu.add_command(label="Change Font Color",
                           command=objFormat.changeFg)
    formatMenu.add_cascade(label="Font", underline=0, menu=fsubmenu)
    formatMenu.add_cascade(label="Size", underline=0, menu=ssubmenu)
    formatMenu.add_command(label="Bold",
                           command=objFormat.bold,
                           accelerator="Ctrl+B")
    formatMenu.add_command(label="Italic",
                           command=objFormat.italic,
                           accelerator="Ctrl+I")
    formatMenu.add_command(label="Underline",
                           command=objFormat.underline,
                           accelerator="Ctrl+U")
    formatMenu.add_command(label="Overstrike",
                           command=objFormat.overstrike,
                           accelerator="Ctrl+T")
    formatMenu.add_command(label="Add Date", command=objFormat.addDate)
    menubar.add_cascade(label="Format", menu=formatMenu)

    root.bind_all("<Control-b>", objFormat.bold)
    root.bind_all("<Control-i>", objFormat.italic)
    root.bind_all("<Control-u>", objFormat.underline)
    root.bind_all("<Control-T>", objFormat.overstrike)

    root.grid_columnconfigure(0, weight=1)
    root.resizable(True, True)

    root.config(menu=menubar)
Пример #30
0
    def show(self, window):
        frame = Frame(window)
        frame.pack()
        title_font = Font(family='Helvetica', size=15, weight="bold", slant="italic")
        Label(frame, text='Material composition', font=title_font).pack(side="top", fill="x", pady=10)

        Label(frame, text="Provide the material's composition by:").pack()
        OptionMenu(frame, self.type_var, "Number of atoms", "Mass fraction",
                   command=self.set_fraction_input_method).pack()
        Label(frame, text="(hover over the headers for explanation)").pack()

        elements_frame = Frame(frame)
        symbol = Label(elements_frame, text="Element (e.g. Au)")
        symbol.grid(row=0, column=0)
        ToolTip(symbol, "The chemical symbol of the element\nfor example for carbon use C")
        self.num_atoms_label = Label(elements_frame, text="Num atoms")
        self.fraction_label = Label(elements_frame, text="Mass frac")
        ToolTip(self.fraction_label, "The fraction of mass (between 0 and 1)")
        self.num_atoms_label.grid(row=0, column=1)

        elements_frame.pack()

        if len(self.elements_dict) == 0:
            self.add_element_and_show(elements_frame)
        else:
            for row in self.elements_dict.keys():
                self.show_element(elements_frame, row)

        Button(frame, text="Add element", command=lambda: self.add_element_and_show(elements_frame)).pack()

        density_frame = Frame(frame)
        Label(density_frame, text="Density (optional):").grid(row=0, column=0)
        Entry(density_frame, textvariable=self.density).grid(row=0, column=1)
        Label(density_frame, text=u"[g/cm\xb3]").grid(row=0, column=2)
        density_frame.pack()
Пример #31
0
    def redraw(self, camera_transform, canvas):
        screen_coords = self.world_vertices_np.dot(camera_transform[:-1].T)

        if self.scale:
            scale = np.linalg.norm(screen_coords[1] - screen_coords[2])
            new_size = int(self.size * scale)
            if new_size != self.current_size and new_size % 5 == 0 and new_size <= 70:
                self.current_size = new_size
                self.cleanup(canvas)

                if new_size >= 10:
                    textId = canvas.create_text(0,
                                                0,
                                                fill=self.color,
                                                text=self.text,
                                                font=Font(size=new_size),
                                                anchor=tk.NW)
                    canvas.addtag_withtag(self.tag, textId)
                    self.element_ids = (textId, )
                else:
                    new_size = 10

        elem_id, = self.element_ids
        x, y = screen_coords[0]
        canvas.coords(elem_id, x, y)
Пример #32
0
    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget("size"))

        self._boldfont = Font(family="helvetica", weight="bold", size=self._size.get())
        self._font = Font(family="helvetica", size=self._size.get())
        if self._size.get() < 0:
            big = self._size.get() - 2
        else:
            big = self._size.get() + 2
        self._bigfont = Font(family="helvetica", weight="bold", size=big)
    def GetFont(self, root, configType, section):
        """Retrieve a font from configuration (font, font-size, font-bold)
        Intercept the special value 'TkFixedFont' and substitute
        the actual font, factoring in some tweaks if needed for
        appearance sakes.

        The 'root' parameter can normally be any valid Tkinter widget.

        Return a tuple (family, size, weight) suitable for passing
        to tkinter.Font
        """
        family = self.GetOption(configType, section, 'font', default='courier')
        size = self.GetOption(configType, section, 'font-size', type='int',
                              default='10')
        bold = self.GetOption(configType, section, 'font-bold', default=0,
                              type='bool')
        if (family == 'TkFixedFont'):
            if TkVersion < 8.5:
                family = 'Courier'
            else:
                f = Font(name='TkFixedFont', exists=True, root=root)
                actualFont = Font.actual(f)
                family = actualFont['family']
                size = actualFont['size']
                if size < 0:
                    size = 10  # if font in pixels, ignore actual size
                bold = actualFont['weight']=='bold'
        return (family, size, 'bold' if bold else 'normal')
Пример #34
0
    def __init__(self, drs, size_canvas=True, canvas=None):
        """
        :param drs: ``AbstractDrs``, The DRS to be drawn
        :param size_canvas: bool, True if the canvas size should be the exact size of the DRS
        :param canvas: ``Canvas`` The canvas on which to draw the DRS.  If none is given, create a new canvas.
        """
        master = None
        if not canvas:
            master = Tk()
            master.title("DRT")

            font = Font(family='helvetica', size=12)

            if size_canvas:
                canvas = Canvas(master, width=0, height=0)
                canvas.font = font
                self.canvas = canvas
                (right, bottom) = self._visit(drs, self.OUTERSPACE,
                                              self.TOPSPACE)

                width = max(right + self.OUTERSPACE, 100)
                height = bottom + self.OUTERSPACE
                canvas = Canvas(master, width=width,
                                height=height)  #, bg='white')
            else:
                canvas = Canvas(master, width=300, height=300)

            canvas.pack()
            canvas.font = font

        self.canvas = canvas
        self.drs = drs
        self.master = master
Пример #35
0
 def __init__(self):
     self.app = Tk()
     self.app.title('Connect4')
     self.app.resizable(width=False, height=False)
     self.board = Board()
     self.buttons = {}
     self.frame = Frame(self.app, borderwidth=1, relief="raised")
     self.tiles = {}
     for x in range(self.board.width):
         handler = lambda x=x: self.move(x)
         button = Button(self.app,
                         command=handler,
                         font=Font(family="Helvetica", size=14),
                         text=x + 1)
         button.grid(row=0, column=x, sticky="WE")
         self.buttons[x] = button
     self.frame.grid(row=1, column=0, columnspan=self.board.width)
     for x, y in self.board.fields:
         tile = Canvas(self.frame,
                       width=60,
                       height=50,
                       bg="navy",
                       highlightthickness=0)
         tile.grid(row=self.board.height - 1 - y, column=x)
         self.tiles[x, y] = tile
     handler = lambda: self.reset()
     self.restart = Button(self.app, command=handler, text='reset')
     self.restart.grid(row=2,
                       column=0,
                       columnspan=self.board.width,
                       sticky="WE")
     self.update()
Пример #36
0
 def __init__(self, wdw, sols):
     """
     Stores the list of solutions in sols
     and defines the layout of the GUI.
     """
     wdw.title('solutions scroller')
     self.sols = sols
     self.cursor = 0
     self.lbl = Label(wdw, text="solution : ")
     self.lbl.grid(row=0, column=0, sticky=E) 
     self.ent = Entry(wdw)
     self.ent.grid(row=0, column=1, stick=W)
     self.ent.insert(INSERT, "0 of %d" % len(sols))
     self.myft = Font(family="Courier New", size=12, weight="normal")
     self.mlen = self.myft.measure("M")
     lines = sols[0].split('\n')
     self.width = max([len(line) for line in lines])
     self.display = StringVar()
     self.display.set(self.sols[0])
     self.mess = Message(wdw, textvariable=self.display, \
         font=self.myft, width=self.width*self.mlen, background='white')
     self.mess.grid(row=1, column=0, columnspan=2)
     self.btnext = Button(wdw, command=self.next, text='next')
     self.btnext.grid(row=2, column=1, sticky=W+E)
     self.btprev = Button(wdw, command=self.previous, text='previous')
     self.btprev.grid(row=2, column=0, sticky=W+E)
Пример #37
0
    def text_size(self):
        """Returns (w, h) of current text according to current font.
        """
        f = Font(family=self.font[0], size=self.font[1])
        # total height of line, I believe
        h = f.metrics('linespace')
#        print "all metrics:"
#        m = f.metrics()
#        for k in m:
#            print "%s: %s" % (k, str(m[k]))
        lines = self.text.splitlines()
        num_lines = len(lines)
        # max line width
        w = max( [f.measure(line) for line in lines] )
        h = num_lines * h
        
        return (w, h)        
Пример #38
0
class TkFont():
    
    def __init__(self, family = "Calibri", weight = NORMAL, slant = ROMAN, overstrike = 0, underline = 0, size = 12):
        '''
        family: 字符集
        size: 字体大小
        weight: "bold" for boldface, "normal" for regular weight.        
        slant: "italic" for italic, "roman" for unslanted.        
        underline: 1 for underlined text, 0 for normal.
        overstrike: 1 for overstruck text, 0 for normal.
        '''
        self.font = Font(family = family, weight = weight, slant = slant, overstrike = overstrike, underline = underline, size = size)
    
    def get_actual_font_info(self):
        return self.font.actual()
    
    def config(self,**kw):
        self.font.config(**kw)
Пример #39
0
def get_font_name(font):
    # create font name
    # i.e. "helvetica 12" -> ("helvetica", 12, "roman", "normal")
    from tkFont import Font
    font_name = None
    try:
        f = Font(font=font)
    except:
        print_err(_('invalid font name: ') + font)
        if DEBUG:
            traceback.print_exc()
    else:
        fa = f.actual()
        font_name = (fa['family'],
                     fa['size'],
                     fa['slant'],
                     fa['weight'])
    return font_name
Пример #40
0
 def __init__(self, family = "Calibri", weight = NORMAL, slant = ROMAN, overstrike = 0, underline = 0, size = 12):
     '''
     family: 字符集
     size: 字体大小
     weight: "bold" for boldface, "normal" for regular weight.        
     slant: "italic" for italic, "roman" for unslanted.        
     underline: 1 for underlined text, 0 for normal.
     overstrike: 1 for overstruck text, 0 for normal.
     '''
     self.font = Font(family = family, weight = weight, slant = slant, overstrike = overstrike, underline = underline, size = size)
Пример #41
0
class Scroller(object):
    """
    Scrolls through a solution list.
    """
    def __init__(self, wdw, sols):
        """
        Stores the list of solutions in sols
        and defines the layout of the GUI.
        """
        wdw.title('solutions scroller')
        self.sols = sols
        self.cursor = 0
        self.lbl = Label(wdw, text="solution : ")
        self.lbl.grid(row=0, column=0, sticky=E) 
        self.ent = Entry(wdw)
        self.ent.grid(row=0, column=1, stick=W)
        self.ent.insert(INSERT, "0 of %d" % len(sols))
        self.myft = Font(family="Courier New", size=12, weight="normal")
        self.mlen = self.myft.measure("M")
        lines = sols[0].split('\n')
        self.width = max([len(line) for line in lines])
        self.display = StringVar()
        self.display.set(self.sols[0])
        self.mess = Message(wdw, textvariable=self.display, \
            font=self.myft, width=self.width*self.mlen, background='white')
        self.mess.grid(row=1, column=0, columnspan=2)
        self.btnext = Button(wdw, command=self.next, text='next')
        self.btnext.grid(row=2, column=1, sticky=W+E)
        self.btprev = Button(wdw, command=self.previous, text='previous')
        self.btprev.grid(row=2, column=0, sticky=W+E)

    def show(self):
        """
        Shows the solution at position self.cursor
        in the message widget and updates the entry widget.
        """
        self.display.set(self.sols[self.cursor])
        self.ent.delete(0, END)
        self.ent.insert(INSERT, '%d of %d' % (self.cursor, len(self.sols)))

    def next(self):
        """
        Increases the cursor by one if possible.
        """
        if self.cursor < len(self.sols) - 1:
            self.cursor = self.cursor + 1
        self.show()

    def previous(self):
        """
        Decreases the cursor by one if possible.
        """
        if self.cursor > 0:
            self.cursor = self.cursor - 1
        self.show()
Пример #42
0
 def _tk_redraw_canvas(self, width, height):
     if self._canvas:
         self._canvas.destroy()
     self._fnormal = Font(family='Monospace', size=13)
     self._fbold = Font(family='Monospace', weight='bold', size=13)
     self._fitalic = Font(family='Monospace', slant='italic', size=13)
     self._fbolditalic = Font(family='Monospace', weight='bold',
                              slant='italic', size=13)
     self._colsize = self._fnormal.measure('A')
     self._rowsize = self._fnormal.metrics('linespace')
     self._canvas = Canvas(self._root, width=self._colsize * width,
                           height=self._rowsize * height)
     self._tk_fill_region(0, height - 1, 0, width - 1)
     self._cursor_row = 0
     self._cursor_col = 0
     self._scroll_top = 0
     self._scroll_bot = height - 1
     self._scroll_left = 0
     self._scroll_right = width - 1
     self._width, self._height = (width, height,)
     self._canvas.pack()
Пример #43
0
  def __init__(self, parent):

	#--- main frame
	main_bg = "black"
	main_fg = "white"
	
	#--- labels
	labFont = Font(family="Courier", size=11)
	labFont.configure(weight = "bold")
	
	#--- pulsanti
	butFont = Font(family="Helvetica", size=11)
	butFont.configure(weight = "bold")
	but_width = 10
	but_height = 0
	but_padx = "3m"
	but_pady = "1m"
	but_relief = FLAT
	but_borderwidth = 1
	but_hlcol = "red"
	but_hlbg = "red"
	but_bg = "#8B0000"
	but_fg = "white"
	but_actbg = "red"
	but_actfg = "white"
	
	#--------------------- fine costanti ----------------

	self.myParent = parent
	
	#--------------------- FRAMES -----------------------
	### Il quadro principale si chiama 'myBox1'
	self.myBox1 = Frame(parent, 
		background=main_bg,
	)
	self.myBox1.pack(side = TOP,
	  fill = BOTH,
	  expand = YES,
	)

	# Il quadro dei pulsanti alto
	self.button_square = Frame(self.myBox1,
		background=main_bg,
		#relief=RAISED, borderwidth=1
	)
	self.button_square.pack(side = TOP,
	  padx=5,
	  pady=5,
	  fill = BOTH,
	  expand = YES,
	)

	# quadro centrale
	self.central_square = Frame(self.myBox1,
		background=main_bg,
		relief=FLAT, borderwidth=1,
		padx = 5,
		pady = 5,
	)
	self.central_square.pack(side = TOP,
	  fill = BOTH,
	  expand = YES,
	  ipadx = 5,
	  ipady = 5,
	)

	# Il quadro dei pulsanti basso
	self.bottom_square = Frame(self.myBox1,
		padx=5,
		pady=5,
		background=main_bg,
		#relief=RAISED, borderwidth=1
	)
	self.bottom_square.pack(side = TOP,
	  fill = BOTH,
	  expand = YES,
	)
	
	# quadro sinistra
	self.left_square = Frame(self.central_square,
		background=main_bg,
		#borderwidth = 5,
		#relief = RIDGE,
	)
	self.left_square.pack(side = LEFT,
	  fill = BOTH,
	  expand = YES,
	)

	# quadro destra
	self.right_square = Frame(self.central_square, 
		background=main_bg,
		#borderwidth = 5,
		#relief = RIDGE,
	)
	self.right_square.pack(side = RIGHT,
	  fill = BOTH,
	  expand = YES,
	)
	#--------------------- FIXED LABELS -----------------------
	# etichette sinistra
	# IP
	self.label1 = Label(self.left_square, 
		background=main_bg, foreground=main_fg,
		text="IP: ", 
		anchor='w', 
		font=labFont,
	)
	self.label1.pack(
		fill=X, 
		expand = YES
	)
	
	# Temp
	self.label2 = Label(self.left_square, 
		background=main_bg, foreground=main_fg,
		text="Temp: ", 
		anchor='w', 
		font=labFont,
	)
	self.label2.pack(
		fill=X, 
		expand = YES
	)
	
	# Date
	self.label3 = Label(self.left_square, 
		background=main_bg, foreground=main_fg,
		text="Date: ", 
		anchor='w', 
		font=labFont,
	)
	self.label3.pack(
		fill=X, 
		expand = YES
	)
	
	# Volts
	self.label4 = Label(self.left_square, 
		background=main_bg, foreground=main_fg,
		text="Core: ", 
		anchor='w', 
		font=labFont,
	)
	self.label4.pack(
		fill=X, 
		expand = YES
	)
	
	# Clock
	self.label5 = Label(self.left_square, 
		background=main_bg, foreground=main_fg,
		text="Clock: ", 
		anchor='w', 
		font=labFont,
	)
	self.label5.pack(
		fill=X, 
		expand = YES
	)
	

	#--------------------- VAR LABELS -----------------------
	# etichette destra
	self.label1var = Label(self.right_square, 
		background=main_bg, foreground=main_fg,
		text=get_ip(), 
		anchor='w', 
		font=labFont,
	)
	self.label1var.pack(
		fill=X, 
		expand = YES
	)
	
	#var_temp = StringVar();
	#var_temp.set(get_temp());
	self.label2var = Label(self.right_square, 
		background=main_bg, foreground=main_fg,
		#textvariable=var_temp, 
		anchor='w', 
		font=labFont,
	)
	self.label2var.pack(
		fill=X, 
		expand = YES
	)
	
	#var_date = StringVar()
	#var_date.set(get_date())
	self.label3var = Label(self.right_square, 
		background=main_bg, foreground=main_fg,
	#	textvariable=var_date, 
		anchor='w', 
		font=labFont,
	)
	self.label3var.pack(
		fill=X, 
		expand = YES
	)
	self.label4var = Label(self.right_square, 
		background=main_bg, foreground=main_fg,
		text=get_volts(), 
		anchor='w', 
		font=labFont,
	)
	self.label4var.pack(
		fill=X, 
		expand = YES
	)
	self.label5var = Label(self.right_square, 
		background=main_bg, foreground=main_fg,
		text=get_clock(), 
		anchor='w', 
		font=labFont,
	)
	self.label5var.pack(
		fill=X, 
		expand = YES
	)
	
	# Vengono ora aggiunti i pulsanti a 'button_square'
	#--------------------- TOP BUTTONS -----------------------
	self.pulsante1 = Button(self.button_square, command = self.buttonPress1)
	self.pulsante1.configure(text = "STARTX")
	self.pulsante1.configure(
	  width = but_width, height = but_height,
	  padx = but_padx, pady = but_pady,
	  relief = but_relief, borderwidth = but_borderwidth, 
	  highlightbackground = but_hlbg, highlightcolor = but_hlcol,
	  activebackground = but_actbg, activeforeground = but_actfg,
	  background = but_bg, foreground = but_fg,
	  font=butFont,
	  )
	self.pulsante1.pack(side = LEFT)
	self.pulsante1.bind("<Return>", self.buttonPress1_a)

	self.pulsante2 = Button(self.button_square, command = self.buttonPress2)
	self.pulsante2.configure(text = "EXIT")
	# default focus
	self.pulsante2.focus_force()
	self.pulsante2.configure(
	  width = but_width, height = but_height,
	  padx = but_padx, pady = but_pady,
	  relief = but_relief, borderwidth = but_borderwidth, 
	  highlightbackground = but_hlbg, highlightcolor = but_hlcol,
	  activebackground = but_actbg, activeforeground = but_actfg,
	  background = but_bg, foreground = but_fg,
	  font=butFont,
	  )
	self.pulsante2.pack(side = RIGHT)
	self.pulsante2.bind("<Return>", self.buttonPress2_a)

	#-------------------- BOTTOM BUTTONS ----------------------
	self.pulsante3 = Button(self.bottom_square, command = self.buttonPress3)
	self.pulsante3.configure(text = "REBOOT")
	self.pulsante3.configure(
	  width = but_width, height = but_height,
	  padx = but_padx, pady = but_pady,
	  relief = but_relief, borderwidth = but_borderwidth, 
	  highlightbackground = but_hlbg, highlightcolor = but_hlcol,
	  activebackground = but_actbg, activeforeground = but_actfg,
	  background = but_bg, foreground = but_fg,
	  font=butFont,
	  )
	self.pulsante3.pack(side = LEFT)
	self.pulsante3.bind("<Return>", self.buttonPress3_a)

	self.pulsante4 = Button(self.bottom_square, command = self.buttonPress4)
	self.pulsante4.configure(text = "SHUTDOWN")
	self.pulsante4.configure(
	  width = but_width, height = but_height,
	  padx = but_padx, pady = but_pady,
	  relief = but_relief, borderwidth = but_borderwidth, 
	  highlightbackground = but_hlbg, highlightcolor = but_hlcol,
	  activebackground = but_actbg, activeforeground = but_actfg,
	  background = but_bg, foreground = but_fg,
	  font=butFont,
	  )
	self.pulsante4.pack(side = RIGHT)
	self.pulsante4.bind("<Return>", self.buttonPress4_a)
Пример #44
0
	def __init__(self, master=None, title=None, buttons=None, default=None,
			help=None, oneshot=None, highlight=None, 
			keepShown=None, resizable=True, *args, **kw):
		if master == None:
			from tkgui import app
			master = app
		else:
			self.overMaster = True
		self._master = master
		self._toplevel = Tk.Toplevel(master, *args, **kw)
		self._toplevel.wm_group(master)
		if not self.overMaster:
			self._idleWaits = 0
			#self._toplevel.bind("<Map>", self._initialPosition)
			self._toplevel.after_idle(self._initialPosition)

		if title:
			self.title = title
		if not self.title:
			self.title = self.name
		if self.title:
			self._toplevel.title(self.title)
		if buttons:
			self.buttons = buttons
		if highlight and not default:
			default = highlight
		if default:
			self.default = default
		if not help is None:
			self.help = help
		if oneshot:
			self.oneshot = oneshot
		if keepShown:
			self.keepShown = keepShown
		if not resizable:
			self._toplevel.wm_resizable(0, 0)
		# 'OK' needs to be able to delay 'oneshot' destruction
		# until after the user-callback returns...
		self.delayOneshot = False
		#sys.__stderr__.write('Create dialog: %s %s\n' %
		#	(self.title, str(self._toplevel)))
		#self._toplevel.bind("<Destroy>", self.Destroy)
		self._toplevel.protocol('WM_DELETE_WINDOW', self.Cancel)
		if isinstance(self.buttons, basestring):
			# compensate for common error of buttons
			# not being a sequence.
			self.buttons = (self.buttons,)
		if Cancel in self.buttons:
			self._toplevel.bind("<Escape>",
						lambda e, c=self.Cancel: c())
		elif Close in self.buttons:
			self._toplevel.bind("<Escape>",
						lambda e, c=self.Close: c())

		bot = Tk.Frame(self._toplevel)
		bot.pack(side=Tk.BOTTOM, fill=Tk.X)
		hr = Tk.Frame(self._toplevel, relief=Tk.GROOVE,
						borderwidth=1, height=2)
		hr.pack(side=Tk.BOTTOM, fill=Tk.X)

		if self.keepShown:
			self.__ksVar = Tkinter.IntVar(bot)
			self.__ksVar.set(False)
			ckbut = Tkinter.Checkbutton(bot, variable=self.__ksVar,
				text="Keep dialog up after %s" % self.keepShown,
				command=self.__keepShownCB)
			from tkFont import Font
			font = Font(font=ckbut.cget('font'))
			font.config(size=int(0.75*float(font.cget('size'))+0.5),
						weight='normal')
			ckbut.config(font=font)
			ckbut.pack(side=Tk.TOP, anchor=Tk.SE)
			self.__keepShownCB() # set up initial button assignment

		if hasattr(self, 'provideStatus') and self.provideStatus:
			slkw = { 'anchor': 'w', 'justify': 'left' }
			if self.statusWidth:
				slkw['width'] = self.statusWidth
			if self.statusPosition == "above":
				slMaster = self._toplevel
			else:
				slMaster = bot
			self.statusLine = Tk.Label(slMaster, **slkw)
			self._statusBlankHandle = None
			if not self.statusResizing:
				self.statusLine.bind('<Map>', self._statusMapCB)
			if self.statusPosition == "above":
				self.statusLine.pack(side=Tk.BOTTOM, fill=Tk.X,
					expand=Tk.NO)
			else:
				self.statusLine.pack(side=Tk.LEFT, fill=Tk.BOTH,
					expand=Tk.YES)
		if self.help:
			import help
			help.register(self._toplevel, self.help)

		self.buttonWidgets = {}
		if resizable:
			sg = Ttk.Sizegrip(bot)
			sg.pack(anchor=Tk.SE, side=Tk.RIGHT)
		self.addSpecialButtons(bot)

		buttons = list(self.buttons[:])	# don't destroy original buttons
		# if Cancel or Close is present, it should be next to Help
		if Cancel in buttons:
			buttons.remove(Cancel)
			self.buttonWidgets[Cancel] = self.__addButton(bot,
						Cancel, self.default is Cancel)
		if Close in buttons:
			buttons.remove(Close)
			self.buttonWidgets[Close] = self.__addButton(bot,
						Close, self.default is Close)
		buttons.reverse()
		for b in buttons:
			self.buttonWidgets[b] = self.__addButton(bot, b,
							self.default == b)
		if self.name:
			import dialogs
			dialogs.reregister(self.name, self)

		# pack last, so that resizing dialog will not occlude
		# action buttons
		self.__top = Tk.Frame(self._toplevel)
		self.__top.pack(side=Tk.TOP, anchor=Tk.W, expand=1,
								fill=Tk.BOTH)
		# do this after pack so that fillInUI can show progress if
		# necessary
		self.fillInUI(self.__top)
Пример #45
0
class DrtGlueDemo(object):
    def __init__(self, examples):
        # Set up the main window.
        self._top = Tk()
        self._top.title('DRT Glue Demo')

        # Set up key bindings.
        self._init_bindings()

        # Initialize the fonts.self._error = None
        self._init_fonts(self._top)

        self._examples = examples
        self._readingCache = [None for example in examples]

        # The user can hide the grammar.
        self._show_grammar = IntVar(self._top)
        self._show_grammar.set(1)

        # Set the data to None
        self._curExample = -1
        self._readings = []
        self._drs = None
        self._drsWidget = None
        self._error = None

        self._init_glue()

        # Create the basic frames.
        self._init_menubar(self._top)
        self._init_buttons(self._top)
        self._init_exampleListbox(self._top)
        self._init_readingListbox(self._top)
        self._init_canvas(self._top)

        # Resize callback
        self._canvas.bind('<Configure>', self._configure)

    #########################################
    ##  Initialization Helpers
    #########################################

    def _init_glue(self):
        tagger = RegexpTagger(
            [('^(David|Mary|John)$', 'NNP'),
             ('^(walks|sees|eats|chases|believes|gives|sleeps|chases|persuades|tries|seems|leaves)$', 'VB'),
             ('^(go|order|vanish|find|approach)$', 'VB'),
             ('^(a)$', 'ex_quant'),
             ('^(every)$', 'univ_quant'),
             ('^(sandwich|man|dog|pizza|unicorn|cat|senator)$', 'NN'),
             ('^(big|gray|former)$', 'JJ'),
             ('^(him|himself)$', 'PRP')
        ])

        depparser = MaltParser(tagger=tagger)
        self._glue = DrtGlue(depparser=depparser, remove_duplicates=False)

    def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = Font(font=Button()["font"])
        root.option_add("*Font", self._sysfont)

        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(root)
        self._size.set(self._sysfont.cget('size'))

        self._boldfont = Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = Font(family='helvetica',
                                    size=self._size.get())
        if self._size.get() < 0: big = self._size.get()-2
        else: big = self._size.get()+2
        self._bigfont = Font(family='helvetica', weight='bold',
                                    size=big)

    def _init_exampleListbox(self, parent):
        self._exampleFrame = listframe = Frame(parent)
        self._exampleFrame.pack(fill='both', side='left', padx=2)
        self._exampleList_label = Label(self._exampleFrame, font=self._boldfont,
                                     text='Examples')
        self._exampleList_label.pack()
        self._exampleList = Listbox(self._exampleFrame, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._exampleList.pack(side='right', fill='both', expand=1)

        for example in self._examples:
            self._exampleList.insert('end', ('  %s' % example))
        self._exampleList.config(height=min(len(self._examples), 25), width=40)

        # Add a scrollbar if there are more than 25 examples.
        if len(self._examples) > 25:
            listscroll = Scrollbar(self._exampleFrame,
                                   orient='vertical')
            self._exampleList.config(yscrollcommand = listscroll.set)
            listscroll.config(command=self._exampleList.yview)
            listscroll.pack(side='left', fill='y')

        # If they select a example, apply it.
        self._exampleList.bind('<<ListboxSelect>>', self._exampleList_select)

    def _init_readingListbox(self, parent):
        self._readingFrame = listframe = Frame(parent)
        self._readingFrame.pack(fill='both', side='left', padx=2)
        self._readingList_label = Label(self._readingFrame, font=self._boldfont,
                                     text='Readings')
        self._readingList_label.pack()
        self._readingList = Listbox(self._readingFrame, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

        self._readingList.pack(side='right', fill='both', expand=1)

        # Add a scrollbar if there are more than 25 examples.
        listscroll = Scrollbar(self._readingFrame,
                               orient='vertical')
        self._readingList.config(yscrollcommand = listscroll.set)
        listscroll.config(command=self._readingList.yview)
        listscroll.pack(side='right', fill='y')

        self._populate_readingListbox()

    def _populate_readingListbox(self):
        # Populate the listbox with integers
        self._readingList.delete(0, 'end')
        for i in range(len(self._readings)):
            self._readingList.insert('end', ('  %s' % (i+1)))
        self._readingList.config(height=min(len(self._readings), 25), width=5)

        # If they select a example, apply it.
        self._readingList.bind('<<ListboxSelect>>', self._readingList_select)

    def _init_bindings(self):
        # Key bindings are a good thing.
        self._top.bind('<Control-q>', self.destroy)
        self._top.bind('<Control-x>', self.destroy)
        self._top.bind('<Escape>', self.destroy)
        self._top.bind('n', self.next)
        self._top.bind('<space>', self.next)
        self._top.bind('p', self.prev)
        self._top.bind('<BackSpace>', self.prev)

    def _init_buttons(self, parent):
        # Set up the frames.
        self._buttonframe = buttonframe = Frame(parent)
        buttonframe.pack(fill='none', side='bottom', padx=3, pady=2)
        Button(buttonframe, text='Prev',
               background='#90c0d0', foreground='black',
               command=self.prev,).pack(side='left')
        Button(buttonframe, text='Next',
               background='#90c0d0', foreground='black',
               command=self.next,).pack(side='left')

    def _configure(self, event):
        self._autostep = 0
        (x1, y1, x2, y2) = self._cframe.scrollregion()
        y2 = event.height - 6
        self._canvas['scrollregion'] = '%d %d %d %d' % (x1,y1,x2,y2)
        self._redraw()

    def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background='white',
                                   #width=525, height=250,
                                   closeenough=10,
                                   border=2, relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        # Initially, there's no tree or text
        self._tree = None
        self._textwidgets = []
        self._textline = None

    def _init_menubar(self, parent):
        menubar = Menu(parent)

        filemenu = Menu(menubar, tearoff=0)
        filemenu.add_command(label='Exit', underline=1,
                             command=self.destroy, accelerator='q')
        menubar.add_cascade(label='File', underline=0, menu=filemenu)

        actionmenu = Menu(menubar, tearoff=0)
        actionmenu.add_command(label='Next', underline=0,
                               command=self.next, accelerator='n, Space')
        actionmenu.add_command(label='Previous', underline=0,
                               command=self.prev, accelerator='p, Backspace')
        menubar.add_cascade(label='Action', underline=0, menu=actionmenu)

        optionmenu = Menu(menubar, tearoff=0)
        optionmenu.add_checkbutton(label='Remove Duplicates', underline=0,
                                   variable=self._glue.remove_duplicates,
                                   command=self._toggle_remove_duplicates,
                                   accelerator='r')
        menubar.add_cascade(label='Options', underline=0, menu=optionmenu)

        viewmenu = Menu(menubar, tearoff=0)
        viewmenu.add_radiobutton(label='Tiny', variable=self._size,
                                 underline=0, value=10, command=self.resize)
        viewmenu.add_radiobutton(label='Small', variable=self._size,
                                 underline=0, value=12, command=self.resize)
        viewmenu.add_radiobutton(label='Medium', variable=self._size,
                                 underline=0, value=14, command=self.resize)
        viewmenu.add_radiobutton(label='Large', variable=self._size,
                                 underline=0, value=18, command=self.resize)
        viewmenu.add_radiobutton(label='Huge', variable=self._size,
                                 underline=0, value=24, command=self.resize)
        menubar.add_cascade(label='View', underline=0, menu=viewmenu)

        helpmenu = Menu(menubar, tearoff=0)
        helpmenu.add_command(label='About', underline=0,
                             command=self.about)
        menubar.add_cascade(label='Help', underline=0, menu=helpmenu)

        parent.config(menu=menubar)

    #########################################
    ##  Main draw procedure
    #########################################

    def _redraw(self):
        canvas = self._canvas

        # Delete the old DRS, widgets, etc.
        if self._drsWidget is not None:
            self._drsWidget.clear()

        if self._drs:
            self._drsWidget = DrsWidget( self._canvas, self._drs )
            self._drsWidget.draw()

        if self._error:
            self._drsWidget = DrsWidget( self._canvas, self._error )
            self._drsWidget.draw()

    #########################################
    ##  Button Callbacks
    #########################################

    def destroy(self, *e):
        self._autostep = 0
        if self._top is None: return
        self._top.destroy()
        self._top = None

    def prev(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or before) the first item
                if index <= 0:
                    self._select_previous_example()
                else:
                    self._readingList_store_selection(index-1)

            else:
                #select its first reading
                self._readingList_store_selection(readingListSize-1)

        else:
            self._select_previous_example()


    def _select_previous_example(self):
        #if the current example is not the first example
        if self._curExample > 0:
            self._exampleList_store_selection(self._curExample-1)
        else:
            #go to the last example
            self._exampleList_store_selection(len(self._examples)-1)

    def next(self, *e):
        selection = self._readingList.curselection()
        readingListSize = self._readingList.size()

        # if there are readings
        if readingListSize > 0:
            # if one reading is currently selected
            if len(selection) == 1:
                index = int(selection[0])

                # if it's on (or past) the last item
                if index >= (readingListSize-1):
                    self._select_next_example()
                else:
                    self._readingList_store_selection(index+1)

            else:
                #select its first reading
                self._readingList_store_selection(0)

        else:
            self._select_next_example()

    def _select_next_example(self):
        #if the current example is not the last example
        if self._curExample < len(self._examples)-1:
            self._exampleList_store_selection(self._curExample+1)
        else:
            #go to the first example
            self._exampleList_store_selection(0)


    def about(self, *e):
        ABOUT = ("NLTK Discourse Representation Theory (DRT) Glue Semantics Demo\n"+
                 "Written by Daniel H. Garrette")
        TITLE = 'About: NLTK DRT Glue Demo'
        try:
            from tkMessageBox import Message
            Message(message=ABOUT, title=TITLE).show()
        except:
            ShowText(self._top, TITLE, ABOUT)

    def postscript(self, *e):
        self._autostep = 0
        self._cframe.print_to_file()

    def mainloop(self, *args, **kwargs):
        """
        Enter the Tkinter mainloop.  This function must be called if
        this demo is created from a non-interactive program (e.g.
        from a secript); otherwise, the demo will close as soon as
        the script completes.
        """
        if in_idle(): return
        self._top.mainloop(*args, **kwargs)

    def resize(self, size=None):
        if size is not None: self._size.set(size)
        size = self._size.get()
        self._font.configure(size=-(abs(size)))
        self._boldfont.configure(size=-(abs(size)))
        self._sysfont.configure(size=-(abs(size)))
        self._bigfont.configure(size=-(abs(size+2)))
        self._redraw()

    def _toggle_remove_duplicates(self):
        self._glue.remove_duplicates = not self._glue.remove_duplicates

        self._exampleList.selection_clear(0, 'end')
        self._readings = []
        self._populate_readingListbox()
        self._readingCache = [None for ex in self._examples]
        self._curExample = -1
        self._error = None

        self._drs = None
        self._redraw()


    def _exampleList_select(self, event):
        selection = self._exampleList.curselection()
        if len(selection) != 1: return
        self._exampleList_store_selection(int(selection[0]))

    def _exampleList_store_selection(self, index):
        self._curExample = index
        example = self._examples[index]

        self._exampleList.selection_clear(0, 'end')
        if example:
            cache = self._readingCache[index]
            if cache:
                if isinstance(cache, list):
                    self._readings = cache
                    self._error = None
                else:
                    self._readings = []
                    self._error = cache
            else:
                try:
                    self._readings = self._glue.parse_to_meaning(example)
                    self._error = None
                    self._readingCache[index] = self._readings
                except Exception, e:
                    self._readings = []
                    self._error = DrtVariableExpression(Variable('Error: ' + str(e)))
                    self._readingCache[index] = self._error

                    #add a star to the end of the example
                    self._exampleList.delete(index)
                    self._exampleList.insert(index, ('  %s *' % example))
                    self._exampleList.config(height=min(len(self._examples), 25), width=40)

            self._populate_readingListbox()

            self._exampleList.selection_set(index)

            self._drs = None
            self._redraw()
Пример #46
0
	def fillInUI(self, parent):
		self._handlers = {}
		desigGroup = Pmw.Group(parent, tag_text="Atoms to Check", hull_padx=2)
		desigGroup.grid(row=0, sticky="ew")
		from chimera.tkgui import windowSystem
		Tkinter.Button(desigGroup.interior(), command=self._desigCB,
				text="Designate").grid(row=0, column=0, sticky='e')
		Tkinter.Label(desigGroup.interior(), text="currently selected"
			" atoms for checking").grid(row=0, column=1, sticky='w')
		self.desigStatus = Tkinter.Label(desigGroup.interior())
		from tkFont import Font
		font = Font(font=self.desigStatus.cget('font'))
		size = int(font.cget('size'))
		if size > 2:
			font.config(size=size-2)
		font.config(weight='normal')
		self.desigStatus.config(font=font)
		from chimera.selection import ItemizedSelection
		self.designated = ItemizedSelection(
					selChangedCB=self._updateDesigStatus)
		self.desigStatus.grid(row=1, column=0, columnspan=2)
		self.designated2 = ItemizedSelection(selChangedCB=self._locButtonCB)
		if windowSystem == 'aqua':
			pady = None
		else:
			pady = 0
		Tkinter.Button(desigGroup.interior(), command=self._desig2CB,
				pady=pady, text="Designate selection as second set"
				).grid(row=3, column=1)
		self.desig2Status = Tkinter.Label(desigGroup.interior())
		if size > 4:
			font2 = Font(font=font)
			font2.config(size=size-4)
		else:
			font2 = font
		self.desig2Status.config(font=font2)
		self.desig2Status.grid(row=4, column=1)
		self.checkLocButtons = Pmw.RadioSelect(desigGroup.interior(),
			pady=0, orient='vertical', buttontype='radiobutton',
			labelpos='w', label_text="Check designated\natoms"
			" against:", command=self._locButtonCB)
		self.checkLocButtons.grid(row=2, column=0, columnspan=2)
		self.checkLocButtons.add("themselves")
		self.checkLocButtons.add("all other atoms")
		self.checkLocButtons.add("other atoms in same model")
		self.checkLocButtons.add(self.CHECK_SET)
		self.checkLocButtons.invoke(1)

		defGroup = Pmw.Group(parent,
			tag_text="Clash/Contact Parameters", hull_padx=2)
		defGroup.grid(row=1, sticky='ew')
		self.clashDef = ClashDef(defGroup.interior(),
					command=self._checkContinuous,
					value=str(prefs[CLASH_THRESHOLD]))
		self.clashDef.grid(row=0, sticky='w')
		self.hbondAllow = HbondAllow(defGroup.interior(),
					command=self._checkContinuous,
					value=str(prefs[HBOND_ALLOWANCE]))
		self.hbondAllow.grid(row=1, sticky='w')
		defaultsFrame = Tkinter.Frame(defGroup.interior())
		defaultsFrame.grid(row=2)
		Tkinter.Label(defaultsFrame, text="Default").grid(
							row=0, column=0)
		Tkinter.Button(defaultsFrame, text="clash", pady=pady,
			command=self._clashDefaultsCB).grid(row=0, column=1)
		Tkinter.Label(defaultsFrame, text="/").grid(row=0, column=2)
		Tkinter.Button(defaultsFrame, text="contact", pady=pady,
			command=self._contactDefaultsCB).grid(row=0, column=3)
		Tkinter.Label(defaultsFrame, text="criteria").grid(
							row=0, column=4)
		bondsFrame = Tkinter.Frame(defGroup.interior())
		bondsFrame.grid(row=3, sticky='w')
		self.bondsApart = Pmw.OptionMenu(bondsFrame, labelpos='w',
			label_text="Ignore contacts of pairs",
			command=self._checkContinuous,
			initialitem=str(prefs[BOND_SEPARATION]),
			items=[str(i+2) for i in range(4)])
		self.bondsApart.grid(row=0, column=0)
		Tkinter.Label(bondsFrame, text="or fewer bonds apart").grid(
							row=0, column=1)
		self.ignoreIntraResVar = Tkinter.IntVar(parent)
		self.ignoreIntraResVar.set(prefs[IGNORE_INTRA_RES])
		Tkinter.Checkbutton(defGroup.interior(), text="Ignore intra-"
			"residue contacts", variable=self.ignoreIntraResVar,
			command=self._checkContinuous
			).grid(row=4)
			
		actionGroup = Pmw.Group(parent, tag_text=
				"Treatment of Clash/Contact Atoms", hull_padx=2)
		actionGroup.grid(row=2, sticky='ew')
		self.actionSelVar = Tkinter.IntVar(parent)
		self.actionSelVar.set(prefs[ACTION_SELECT])
		Tkinter.Checkbutton(actionGroup.interior(), text="Select",
			command=self._checkContinuous,
			variable=self.actionSelVar).grid(row=0, sticky='w')
		self.actionColorVar = Tkinter.IntVar(parent)
		self.actionColorVar.set(prefs[ACTION_COLOR])
		f = Tkinter.Frame(actionGroup.interior())
		f.grid(row=1, sticky='w')
		Tkinter.Checkbutton(f, text="Color",
			command=self._checkContinuous,
			variable=self.actionColorVar).grid(row=0, column=0)
		from CGLtk.color.ColorWell import ColorWell
		self.clashColorWell = ColorWell(f, noneOkay=True,
						callback=self._checkContinuous,
						color=prefs[CLASH_COLOR])
		self.clashColorWell.grid(row=0, column=1)
		Tkinter.Label(f, text=" (and color all other atoms").grid(row=0,
								column=2)
		self.nonclashColorWell = ColorWell(f, noneOkay=True,
						callback=self._checkContinuous,
						color=prefs[NONCLASH_COLOR])
		self.nonclashColorWell.grid(row=0, column=3)
		Tkinter.Label(f, text=")").grid(row=0, column=4)
		self.actionPBVar = Tkinter.IntVar(parent)
		self.actionPBVar.set(prefs[ACTION_PSEUDOBONDS])
		f = Tkinter.Frame(actionGroup.interior())
		f.grid(row=2, sticky='w')
		Tkinter.Checkbutton(f, text="Draw pseudobonds of color",
			command=self._checkContinuous,
			variable=self.actionPBVar).grid(row=0, column=0)
		from CGLtk.color.ColorWell import ColorWell
		self.pbColorWell = ColorWell(f, noneOkay=False,
						callback=self._checkContinuous,
						color=prefs[PB_COLOR])
		self.pbColorWell.grid(row=0, column=1)
		self.pbWidthEntry = Pmw.EntryField(f, labelpos='w',
			label_text=" and width", validate={'validator': 'real',
			'min': 0.01}, entry_width=4, entry_justify="center",
			command=self._checkContinuous,
			value=str(prefs[PB_WIDTH]))
		self.pbWidthEntry.grid(row=0, column=2)
		self.actionAttrVar = Tkinter.IntVar(parent)
		self.actionAttrVar.set(prefs[ACTION_ATTR])
		self.assignAttrButton = Tkinter.Checkbutton(
					actionGroup.interior(),
					text="Assign 'overlap' attribute",
					variable=self.actionAttrVar)
		self.assignAttrButton.grid(row=3, sticky='w')
		self.actionWriteInfoVar = Tkinter.IntVar(parent)
		self.actionWriteInfoVar.set(prefs[ACTION_WRITEINFO])
		self.writeInfoButton = Tkinter.Checkbutton(
			actionGroup.interior(), text="Write information to"
			" file", variable=self.actionWriteInfoVar)
		self.writeInfoButton.grid(row=4, sticky='w')
		self.actionLogInfoVar = Tkinter.IntVar(parent)
		self.actionLogInfoVar.set(prefs[ACTION_REPLYLOG])
		self.logInfoButton = Tkinter.Checkbutton(
			actionGroup.interior(), text="Write information to"
			" reply log", variable=self.actionLogInfoVar)
		self.logInfoButton.grid(row=5, sticky='w')

		freqGroup = Pmw.Group(parent, tag_text="Frequency of Checking",
								hull_padx=2)
		freqGroup.grid(row=3, sticky="ew")
		self.freqButtons = Pmw.RadioSelect(freqGroup.interior(),
			pady=0, orient='vertical', buttontype='radiobutton',
			labelpos='w', label_text= "Check...",
			command=self._freqChangeCB)
		self.freqButtons.grid(sticky='w')
		self.freqButtons.add(self.FREQ_APPLY)
		self.freqButtons.add(self.FREQ_MOTION)
		self.freqButtons.add(self.FREQ_CONTINUOUS)

		self.freqButtons.invoke(0)
		self._updateDesigStatus()
Пример #47
0
class TextTable(Frame,object):
	def __init__(self,parent,frames=None,aligns=None,weights=None,**kwargs):
		Frame.__init__(self,parent,**kwargs)
		self.numberOfRows=0
		self.aligns = aligns
		if not self.aligns:
			self.aligns = ["left","left","left","left","left","left"]
		if not weights:
			weights=[1,1,1,1]
		if frames==None:
			self.frames=["one","two","three","four","five","six"]
		else:
			self.frames=frames
		# for i in range(0,len(self.frames)):
		# 	self.frames[i]=Frame(self)
		# 	self.frames[i].grid(side=LEFT,expand=1,fill=BOTH)

		self.textBoxes=[]
		for i in range(0,len(self.frames)):
			self.textBoxes.append(Text(self,bd=0,width=0,state='disabled'))
			self.textBoxes[-1].grid(row=0,column=i,sticky=W+E+N+S)
			self.textBoxes[-1].tag_configure("right",justify="right",wrap=NONE)
			self.textBoxes[-1].tag_configure("center",justify="center",wrap=NONE)
			self.textBoxes[-1].tag_configure("left",justify="left",wrap=NONE)
			self.textBoxes[-1].tag_configure("underline",underline=True)
			self.grid_columnconfigure(i,weight=weights[i])
		self.grid_rowconfigure(0,weight=1)
		self.boldFont = Font(self.textBoxes[0],self.textBoxes[0].cget('font'))
		self.boldFont.configure(weight='bold')
		for i in self.textBoxes:
			i.tag_configure("bold",font=self.boldFont)


	def fixAligns(self):
		for i in range(0,len(self.textBoxes)):
			self.textBoxes[i]['state']='normal'
			self.textBoxes[i].tag_add(self.aligns[i],'1.0','end')
			self.textBoxes[i]['state']='disabled'

	def addRow(self,values,uls=None,bolds=None):
		self.numberOfRows+=1
		for i in range(0,len(self.textBoxes)):
			self.textBoxes[i]['state']='normal'
			if self.numberOfRows==1:
				self.textBoxes[i].insert(self.textBoxes[i].index("end"),values[i])
			else:
				self.textBoxes[i].insert(self.textBoxes[i].index("end"),"\n"+values[i])
			self.textBoxes[i]['state']='disabled'

		if uls:
			for i in range(0,len(uls)):
				if uls[i]:
					self.textBoxes[i]['state']='normal'
					self.textBoxes[i].tag_add("underline",'end - 1 line','end -1 line lineend')
					self.textBoxes[i]['state']='disabled'
		if bolds:
			for i in range(0,len(bolds)):
				if bolds[i]:
					self.textBoxes[i]['state']='normal'
					self.textBoxes[i].tag_add("bold","end -1 line",'end -1 line lineend')
					self.textBoxes[i]['state']='disabled'
		self.fixAligns()
		for i in self.textBoxes:
			i.configure(height=self.numberOfRows)

	def clear(self):
		for i in self.textBoxes:
			i['state']='normal'
			i.delete("1.0","end")
			i['state']='disabled'
		self.numberOfRows=0

	def getLine(self,index):
		vals = []
		for i in self.textBoxes:
			vals.append(i.get(str(index)+".0",str(index)+".end"))

		return vals
Пример #48
0
    def __init__(self, master, columns, data=None, command=None, sort=True, select_mode=None, heading_anchor = CENTER, cell_anchor=W, style=None, height=None, padding=None, adjust_heading_to_content=False, stripped_rows=None, selection_background=None, selection_foreground=None, field_background=None, heading_font= None, heading_background=None, heading_foreground=None, cell_pady=2, cell_background=None, cell_foreground=None, cell_font=None, headers=True):

        self._stripped_rows = stripped_rows

        self._columns = columns
        
        self._number_of_rows = 0
        self._number_of_columns = len(columns)
        
        self.row = self.List_Of_Rows(self)
        self.column = self.List_Of_Columns(self)
        
        s = Style()

        if style is None:
            style_name = "Multicolumn_Listbox%s.Treeview"%self._style_index
            self._style_index += 1
        else:
            style_name = style
        
        style_map = {}
        if selection_background is not None:
            style_map["background"] = [('selected', selection_background)]
            
        if selection_foreground is not None:
            style_map["foeground"] = [('selected', selection_foreground)]

        if style_map:
            s.map(style_name, **style_map)

        style_config = {}
        if cell_background is not None:
            style_config["background"] = cell_background

        if cell_foreground is not None:
            style_config["foreground"] = cell_foreground

        if cell_font is None:
            font_name = s.lookup(style_name, "font")
            cell_font = nametofont(font_name)
        else:
            if not isinstance(cell_font, Font):
                if isinstance(cell_font, basestring):
                    cell_font = nametofont(cell_font)
                else:
                    if len(font) == 1:
                        cell_font = Font(family=cell_font[0])
                    elif len(font) == 2:
                        cell_font = Font(family=cell_font[0], size=cell_font[1])
                        
                    elif len(font) == 3:
                        cell_font = Font(family=cell_font[0], size=cell_font[1], weight=cell_font[2])
                    else:
                        raise ValueError("Not possible more than 3 values for font")
        
            style_config["font"] = cell_font
        
        self._cell_font = cell_font

        self._rowheight = cell_font.metrics("linespace")+cell_pady
        style_config["rowheight"]=self._rowheight

        if field_background is not None:
            style_config["fieldbackground"] = field_background

        s.configure(style_name, **style_config)

        heading_style_config = {}
        if heading_font is not None:
            heading_style_config["font"] = heading_font
        if heading_background is not None:
            heading_style_config["background"] = heading_background
        if heading_foreground is not None:
            heading_style_config["foreground"] = heading_foreground

        heading_style_name = style_name + ".Heading"
        s.configure(heading_style_name, **heading_style_config)

        treeview_kwargs = {"style": style_name}

        if height is not None:
            treeview_kwargs["height"] = height
            
        if padding is not None:
            treeview_kwargs["padding"] = padding
            
        if headers:
            treeview_kwargs["show"] = "headings"
        else:
            treeview_kwargs["show"] = ""
        
        if select_mode is not None:
            treeview_kwargs["selectmode"] = select_mode

        self.interior = Treeview(master, columns=columns, **treeview_kwargs)
        
        if command is not None:
            self._command = command
            self.interior.bind("<<TreeviewSelect>>", self._on_select)

        for i in range(0, self._number_of_columns):

            if sort:
                self.interior.heading(i, text=columns[i], anchor=heading_anchor, command=lambda col=i: self.sort_by(col, descending=False))
            else:
                self.interior.heading(i, text=columns[i], anchor=heading_anchor)
                
            if adjust_heading_to_content:
                self.interior.column(i, width=Font().measure(columns[i]))

            self.interior.column(i, anchor=cell_anchor)
            
        if data is not None:
            for row in data:
                self.insert_row(row)
Пример #49
0
	def body(self):
		fnt = Font(family="Arial", size=10)
		self.tbl_fnt = fnt
				
		num_len       = max(fnt.measure(_("clm_num")), fnt.measure("9999"))
		word_len      = max(fnt.measure(_("clm_word")), fnt.measure(_("clm_transcription")), fnt.measure(_("clm_translate")))
		cnt_len       = max(fnt.measure("9999"), fnt.measure(_("clm_cnt_suc")), fnt.measure(_("clm_cnt_err")))
		prs_len       = max(fnt.measure("100.0%"), fnt.measure(_("clm_pers_suc")))
		state_len     = max(fnt.measure(_("st_learn")), fnt.measure(_("st_learned")), fnt.measure(_("st_study")), fnt.measure(_("clm_state")))
		self.len_clmn = [num_len, word_len, word_len, word_len, cnt_len, cnt_len, prs_len, state_len]

		# Находим слова с большей длинной, чем умолчательная
		for stat in self.statistic.get_ru_en():
			for it in range(1, 4):
				if len(stat[it]) > 10:
					self.len_clmn[it] = max(self.len_clmn[it], fnt.measure(stat[it]))

		self.len_clmn = [i+20 for i in self.len_clmn]

		Label(self, text="", bg=clr_tbl_bg[0]).grid(row=0, column=0, sticky=W+E, padx=2)
		self.btRuEn = Button(self, text=_("btn_ru_en"), command=self.show_ru_en)
		self.btRuEn.grid(row=0, column=1, sticky=W+E, pady=5, padx=1)
		self.btEnRu = Button(self, text=_("btn_en_ru"), command=self.show_en_ru)
		self.btEnRu.grid(row=0, column=2, sticky=W+E, pady=5, padx=1)
		self.btCmnStat = Button(self, text=_("btn_common_stat"), command=self.show_common_stat)
		self.btCmnStat.grid(row=0, column=3, sticky=W+E, pady=5, padx=1)

		self.canvas = ScrollCanvas(self)
		self.canvas.grid(row=1, column=1, columnspan=5)

		self.grid_rowconfigure(1, weight=1)
		self.grid_columnconfigure(1, weight=1)
		self.grid_columnconfigure(2, weight=1)
		self.grid_columnconfigure(3, weight=1)

		self.show_ru_en()

		self.canvas.config(scrollregion=self.canvas.bbox("all"))
Пример #50
0
	def fillInUI(self, parent):
		import Pmw, Tkinter
		self.buttonWidgets['OK']['state'] = 'disabled'
		self.buttonWidgets['Apply']['state'] = 'disabled'
		from chimera.widgets import ModelScrolledListBox
		self.surfListBox = ModelScrolledListBox(parent, labelpos='n',
			label_text='Surfaces to color by ESP:',
			listbox_selectmode="extended",
			filtFunc=lambda m: isinstance(m, chimera.MSMSModel),
			selectioncommand=self._selSurfCB)
		self.surfListBox.grid(row=0, column=0, sticky="nsew",
							columnspan=2)
		Pmw.OptionMenu(parent, command=self._menuCB, initialitem="3",
			items=[str(x) for x in range(2, 12)], labelpos='w',
			label_text="Number of colors/values:").grid(row=1,
			column=0, columnspan=2)
		f = self.interpFrame = Tkinter.Frame(parent)
		f.grid(row=2, column=0, columnspan=2)
		self.wells = []
		self.values = []
		self._entryOpts = {
			'validate': 'real',
			'entry_justify': 'center',
			'entry_width': 6
		}
		from CGLtk.color.ColorWell import ColorWell
		for color, value in [("red", -10), ("white", 0), ("blue", 10)]:
			well = ColorWell(f, color=color)
			well.grid(row=0, column=len(self.wells))
			self.wells.append(well)
			entry = Pmw.EntryField(f, value=str(value),
							**self._entryOpts)
			entry.grid(row=1, column=len(self.values))
			self.values.append(entry)

		from chimera.tkoptions import FloatOption, BooleanOption
		self.distDep = BooleanOption(parent, 3,
			"Distance-dependent dielectric", True, None, balloon=
			"If true, charge falls off with distance squared to\n"
			"simulate solvent screening effects")
		self.dielectric = FloatOption(parent, 4, "Dielectric constant",
								4.0, None)
		self.surfDist = FloatOption(parent, 5, "Distance from surface",
			1.4, None, balloon="Potential at this distance from\n"
			"the surface is used for coloring")

		self.hisGroup = Pmw.Group(parent, hull_padx=2,
			tag_text="Implicit Histidine Protonation")
		self.hisGroup.grid(row=6, column=0, columnspan=2, sticky="nsew")
		self.hisProtVar = Tkinter.StringVar(parent)
		self.hisProtVar.set("name")
		interior = self.hisGroup.interior()
		interior.columnconfigure(0, weight=1)
		lab = Tkinter.Label(interior, text="Assumed histidine "
			"protonation for\nstructures without explicit hydrogens")
		from tkFont import Font
		font = Font(font=lab.cget('font'))
		font.config(size=int(0.75 * float(font.cget('size'))),
								slant='italic')
		lab.config(font=font)
		lab.grid(row=0)
		Tkinter.Radiobutton(interior, variable=self.hisProtVar,
			value="name", text="Residue name-based", command=
			self._switchHisList).grid(row=1, sticky='w')
		f = Tkinter.Frame(interior)
		f.grid(row=2)
		Tkinter.Label(f, text="HID/HIE/HIP = delta/epsilon/both").grid(
			row=0, sticky='w')
		self.hisDefault = Pmw.OptionMenu(f, initialitem=self.HB,
			items=[self.HB, "delta", "epsilon", "both"], labelpos='w',
			label_text="HIS = ", command=lambda a, s=self:
			setattr(s, 'hisChanged', True))
		self.hisDefault.grid(row=1, sticky='w')
		self._pickText = Tkinter.StringVar(parent)
		self._pickText.set("Specified individually...")
		Tkinter.Radiobutton(interior, variable=self.hisProtVar,
			value="pick", textvariable=self._pickText,
			command=self._switchHisList).grid(row=3, sticky='w')

		Tkinter.Button(parent, pady=0, command=self._colorKeyCB,
			text="Create corresponding color key").grid(row=7,
			column=0, columnspan=2)
		self.hisChanged = False
Пример #51
0
import Tkinter
from tkFont import Font

# weight/slant
NORMAL = "normal"
BOLD   = "bold"
ITALIC = "italic"

root = Tkinter.Tk()

def families(root=None):
    "Get font families (as a tuple)"
    if not root:
        root = Tkinter._default_root
    return root.tk.splitlist(root.tk.call("font", "families"))
def names(root=None):
    "Get names of defined fonts (as a tuple)"
    if not root:
        root = Tkinter._default_root
    return root.tk.splitlist(root.tk.call("font", "names"))
# create a font
f = Font(family="times", size=30, weight=NORMAL)
print f.actual()
print f.actual("family")
print f.actual("weight")
print f.config()
print f.cget("family")
print f.cget("weight")
print names()
Пример #52
-2
class NvimTk(object):

    """Wraps all nvim/tk event handling."""

    def __init__(self, nvim):
        """Initialize with a Nvim instance."""
        self._nvim = nvim
        self._attrs = {}
        self._nvim_updates = deque()
        self._canvas = None
        self._fg = '#000000'
        self._bg = '#ffffff'

    def run(self):
        """Start the UI."""
        self._tk_setup()
        t = Thread(target=self._nvim_event_loop)
        t.daemon = True
        t.start()
        self._root.mainloop()

    def _tk_setup(self):
        self._root = Tk()
        self._root.bind('<<nvim_redraw>>', self._tk_nvim_redraw)
        self._root.bind('<<nvim_detach>>', self._tk_nvim_detach)
        self._root.bind('<Key>', self._tk_key)

    def _tk_nvim_redraw(self, *args):
        update = self._nvim_updates.popleft()
        for update in update:
            handler = getattr(self, '_tk_nvim_' + update[0])
            for args in update[1:]:
                handler(*args)

    def _tk_nvim_detach(self, *args):
        self._root.destroy()

    def _tk_nvim_resize(self, width, height):
        self._tk_redraw_canvas(width, height)

    def _tk_nvim_clear(self):
        self._tk_clear_region(0, self._height - 1, 0, self._width - 1)

    def _tk_nvim_eol_clear(self):
        row, col = (self._cursor_row, self._cursor_col,)
        self._tk_clear_region(row, row, col, self._scroll_right)

    def _tk_nvim_cursor_goto(self, row, col):
        self._cursor_row = row
        self._cursor_col = col

    def _tk_nvim_cursor_on(self):
        pass

    def _tk_nvim_cursor_off(self):
        pass

    def _tk_nvim_mouse_on(self):
        pass

    def _tk_nvim_mouse_off(self):
        pass

    def _tk_nvim_insert_mode(self):
        pass

    def _tk_nvim_normal_mode(self):
        pass

    def _tk_nvim_set_scroll_region(self, top, bot, left, right):
        self._scroll_top = top
        self._scroll_bot = bot
        self._scroll_left = left
        self._scroll_right = right

    def _tk_nvim_scroll(self, count):
        top, bot = (self._scroll_top, self._scroll_bot,)
        left, right = (self._scroll_left, self._scroll_right,)

        if count > 0:
            destroy_top = top
            destroy_bot = top + count - 1
            move_top = destroy_bot + 1
            move_bot = bot
            fill_top = move_bot + 1
            fill_bot = fill_top + count - 1
        else:
            destroy_top = bot + count + 1
            destroy_bot = bot
            move_top = top
            move_bot = destroy_top - 1
            fill_bot = move_top - 1
            fill_top = fill_bot + count + 1

        # destroy items that would be moved outside the scroll region after
        # scrolling
        # self._tk_clear_region(destroy_top, destroy_bot, left, right)
        # self._tk_clear_region(move_top, move_bot, left, right)
        self._tk_destroy_region(destroy_top, destroy_bot, left, right)
        self._tk_tag_region('move', move_top, move_bot, left, right)
        self._canvas.move('move', 0, -count * self._rowsize)
        self._canvas.dtag('move', 'move')
        # self._tk_fill_region(fill_top, fill_bot, left, right)

    def _tk_nvim_highlight_set(self, attrs):
        self._attrs = attrs

    def _tk_nvim_put(self, data):
        # choose a Font instance
        font = self._fnormal
        if self._attrs.get('bold', False):
            font = self._fbold
        if self._attrs.get('italic', False):
            font = self._fbolditalic if font == self._fbold else self._fitalic
        # colors
        fg = "#{0:0{1}x}".format(self._attrs.get('foreground', self._fg), 6)
        bg = "#{0:0{1}x}".format(self._attrs.get('background', self._bg), 6)
        # get the "text" and "rect" which correspond to the current cell
        x, y = self._tk_get_coords(self._cursor_row, self._cursor_col)
        items = self._canvas.find_overlapping(x, y, x + 1, y + 1)
        if len(items) != 2:
            # caught part the double-width character in the cell to the left,
            # filter items which dont have the same horizontal coordinate as
            # "x"
            predicate = lambda item: self._canvas.coords(item)[0] == x
            items = filter(predicate, items)
        # rect has lower id than text, sort to unpack correctly
        rect, text = sorted(items)
        self._canvas.itemconfig(text, fill=fg, font=font, text=data or ' ')
        self._canvas.itemconfig(rect, fill=bg)
        self._tk_nvim_cursor_goto(self._cursor_row, self._cursor_col + 1)

    def _tk_nvim_bell(self):
        self._root.bell()

    def _tk_nvim_update_fg(self, fg):
        self._fg = "#{0:0{1}x}".format(fg, 6)

    def _tk_nvim_update_bg(self, bg):
        self._bg = "#{0:0{1}x}".format(bg, 6)

    def _tk_redraw_canvas(self, width, height):
        if self._canvas:
            self._canvas.destroy()
        self._fnormal = Font(family='Monospace', size=13)
        self._fbold = Font(family='Monospace', weight='bold', size=13)
        self._fitalic = Font(family='Monospace', slant='italic', size=13)
        self._fbolditalic = Font(family='Monospace', weight='bold',
                                 slant='italic', size=13)
        self._colsize = self._fnormal.measure('A')
        self._rowsize = self._fnormal.metrics('linespace')
        self._canvas = Canvas(self._root, width=self._colsize * width,
                              height=self._rowsize * height)
        self._tk_fill_region(0, height - 1, 0, width - 1)
        self._cursor_row = 0
        self._cursor_col = 0
        self._scroll_top = 0
        self._scroll_bot = height - 1
        self._scroll_left = 0
        self._scroll_right = width - 1
        self._width, self._height = (width, height,)
        self._canvas.pack()

    def _tk_fill_region(self, top, bot, left, right):
        # create columns from right to left so the left columns have a
        # higher z-index than the right columns. This is required to
        # properly display characters that cross cell boundary
        for rownum in range(bot, top - 1, -1):
            for colnum in range(right, left - 1, -1):
                x1 = colnum * self._colsize
                y1 = rownum * self._rowsize
                x2 = (colnum + 1) * self._colsize
                y2 = (rownum + 1) * self._rowsize
                # for each cell, create two items: The rectangle is used for
                # filling background and the text is for cell contents.
                self._canvas.create_rectangle(x1, y1, x2, y2,
                                              fill=self._background, width=0)
                self._canvas.create_text(x1, y1, anchor='nw',
                                         font=self._fnormal, width=1,
                                         fill=self._foreground, text=' ')

    def _tk_clear_region(self, top, bot, left, right):
        self._tk_tag_region('clear', top, bot, left, right)
        self._canvas.itemconfig('clear', fill=self._bg)
        self._canvas.dtag('clear', 'clear')

    def _tk_destroy_region(self, top, bot, left, right):
        self._tk_tag_region('destroy', top, bot, left, right)
        self._canvas.delete('destroy')
        self._canvas.dtag('destroy', 'destroy')

    def _tk_tag_region(self, tag, top, bot, left, right):
        x1, y1 = self._tk_get_coords(top, left)
        x2, y2 = self._tk_get_coords(bot, right)
        self._canvas.addtag_overlapping(tag, x1, y1, x2 + 1, y2 + 1)

    def _tk_get_coords(self, row, col):
        x = col * self._colsize
        y = row * self._rowsize
        return x, y

    def _tk_key(self, event):
        if 0xffe1 <= event.keysym_num <= 0xffee:
            # this is a modifier key, ignore. Source:
            # https://www.tcl.tk/man/tcl8.4/TkCmd/keysyms.htm
            return
        # Translate to Nvim representation of keys
        send = []
        if event.state & 0x1:
            send.append('S')
        if event.state & 0x4:
            send.append('C')
        if event.state & (0x8 | 0x80):
            send.append('A')
        special = len(send) > 0
        key = event.char
        if _is_invalid_key(key):
            special = True
            key = event.keysym
        send.append(SPECIAL_KEYS.get(key, key))
        send = '-'.join(send)
        if special:
            send = '<' + send + '>'
        nvim = self._nvim
        nvim.session.threadsafe_call(lambda: nvim.input(send))

    def _nvim_event_loop(self):
        self._nvim.session.run(self._nvim_request,
                               self._nvim_notification,
                               lambda: self._nvim.attach_ui(80, 24))
        self._root.event_generate('<<nvim_detach>>', when='tail')

    def _nvim_request(self, method, args):
        raise Exception('This UI does not implement any methods')

    def _nvim_notification(self, method, args):
        if method == 'redraw':
            self._nvim_updates.append(args)
            self._root.event_generate('<<nvim_redraw>>', when='tail')