Python tkinter.font() Examples

The following are 30 code examples of tkinter.font(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module tkinter , or try the search function .
Example #1
Source File: rdparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def _init_fonts(self, root):
        # See: <http://www.astro.washington.edu/owen/ROTKFolklore.html>
        self._sysfont = tkinter.font.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 = tkinter.font.Font(family='helvetica', weight='bold',
                                    size=self._size.get())
        self._font = tkinter.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 = tkinter.font.Font(family='helvetica', weight='bold',
                                    size=big) 
Example #2
Source File: UICommon.py    From RaspberryPiBarcodeScanner with MIT License 6 votes vote down vote up
def table(self, master, title, content, target=None, backgroundcolour="White", foregroundcolour="black", bordercolour="grey", borderwidth=1, fontstyle="DejaVuSans 18 normal"):
        # creates a table from a 2 dimensional array.  
        # master: = this represents the parent window
        # content: a 2 dimensional array containing the table contents
        # First column in the array must be the row id which is returned on a click event.  This will not be displayed in the table
        index = 0
        for i in range(len(content)): #Rows
            for j in range(len(content[i])):
                if j==0: 
                    index = content[i][j]
                else:
                    b = tk.Label(master, text=str(content[i][j]), background=backgroundcolour, foreground=foregroundcolour,padx=5, pady=10, highlightthickness=borderwidth, highlightbackground=bordercolour, font=fontstyle)
                    if (target is not None):
                        b.bind('<ButtonPress-1>', self.__row_pressed)  
                        b.bind('<ButtonRelease-1>', lambda event, arg1=index, arg2=target: self.__row_released(event, arg1, arg2))                 
                    b.grid(row=i, column=j-1, sticky=tk.N+tk.S+tk.E+tk.W)
        return 
Example #3
Source File: chartparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def _draw_sentence(self):
        """Draw the sentence string."""
        if self._chart.num_leaves() == 0: return
        c = self._sentence_canvas
        margin = ChartView._MARGIN
        y = ChartView._MARGIN

        for i, leaf in enumerate(self._chart.leaves()):
            x1 = i * self._unitsize + margin
            x2 = x1 + self._unitsize
            x = (x1+x2)/2
            tag = c.create_text(x, y, text=repr(leaf),
                                font=self._font,
                                anchor='n', justify='left')
            bbox = c.bbox(tag)
            rt=c.create_rectangle(x1+2, bbox[1]-(ChartView._LEAF_SPACING/2),
                                  x2-2, bbox[3]+(ChartView._LEAF_SPACING/2),
                                  fill='#f0f0f0', outline='#f0f0f0')
            c.tag_lower(rt) 
Example #4
Source File: gui.py    From synthesizer with GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, master, audio):
        super().__init__(master)
        self.buttons = []
        self.columns = 6
        self.rows = 4
        self.font = tkinter.font.Font(family="Helvetica", size=22, weight="bold")
        self.audio = audio
        keys = ["1234567890", "qwertyuiop", "asdfghjkl;", "zxcvbnm,./"]
        for y in range(self.rows):
            for x in range(self.columns):
                key = keys[y][x]
                button = tkinter.Button(self, text=str(key), height=5, width=10, padx=24, pady=20)
                button["font"] = self.font
                button.hotkey = key
                button.dk_instrument = None
                button.bind("<Button-1>", lambda x=x, y=y, button=button: self.pressed(button))
                button.grid(row=y, column=x)
                self.buttons.append(button) 
Example #5
Source File: mainwindow_ui.py    From pydiff with MIT License 6 votes vote down vote up
def create_line_numbers(self):
        self.leftLinenumbers = Text(self.main_window, width=3, padx=5, pady=5, height=1, bg=self.lightGrayColor)
        self.leftLinenumbers.grid(row=self.lineNumbersRow, column=self.leftLineNumbersCol, sticky=NS)
        self.leftLinenumbers.config(font=self.text_area_font)
        self.leftLinenumbers.tag_configure('line', justify='right')

        self.rightLinenumbers = Text(self.main_window, width=3, padx=5, pady=5, height=1, bg=self.lightGrayColor)
        self.rightLinenumbers.grid(row=self.lineNumbersRow, column=self.rightLineNumbersCol, sticky=NS)
        self.rightLinenumbers.config(font=self.text_area_font)
        self.rightLinenumbers.tag_configure('line', justify='right')

        # disable the line numbers
        self.leftLinenumbers.config(state=DISABLED)
        self.rightLinenumbers.config(state=DISABLED)

    # Scroll bars 
Example #6
Source File: srparser_app.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def _init_canvas(self, parent):
        self._cframe = CanvasFrame(parent, background='white',
                                   width=525, closeenough=10,
                                   border=2, relief='sunken')
        self._cframe.pack(expand=1, fill='both', side='top', pady=2)
        canvas = self._canvas = self._cframe.canvas()

        self._stackwidgets = []
        self._rtextwidgets = []
        self._titlebar = canvas.create_rectangle(0,0,0,0, fill='#c0f0f0',
                                                 outline='black')
        self._exprline = canvas.create_line(0,0,0,0, dash='.')
        self._stacktop = canvas.create_line(0,0,0,0, fill='#408080')
        size = self._size.get()+4
        self._stacklabel = TextWidget(canvas, 'Stack', color='#004040',
                                      font=self._boldfont)
        self._rtextlabel = TextWidget(canvas, 'Remaining Text',
                                      color='#004040', font=self._boldfont)
        self._cframe.add_widget(self._stacklabel)
        self._cframe.add_widget(self._rtextlabel)

    #########################################
    ##  Main draw procedure
    ######################################### 
Example #7
Source File: zynthian_gui_songeditor.py    From zynthian-ui with GNU General Public License v3.0 6 votes vote down vote up
def drawGrid(self, clearGrid = False):
		font = tkFont.Font(family=zynthian_gui_config.font_topbar[0], size=self.fontsize)
		if clearGrid:
			self.gridCanvas.delete(tkinter.ALL)
			self.columnWidth = self.gridWidth / self.horizontalZoom
			self.trackTitleCanvas.delete("trackname")
		self.playCanvas.delete("timetext")
		# Draw cells of grid
		self.gridCanvas.itemconfig("gridcell", fill=CELL_BACKGROUND)
		for row in range(self.verticalZoom):
			if row >= len(self.tracks):
				break
			if clearGrid:
				self.trackTitleCanvas.create_text((0, self.rowHeight * (row + 0.5)), text="Track %d" % (self.tracks[row]), font=font, fill=CELL_FOREGROUND, tags=("rowtitle%d" % (row),"trackname"), anchor="w")
				self.gridCanvas.create_text(self.gridWidth - self.selectThickness, self.rowHeight * (self.rowHeight * int(row + 0.5)), state="hidden", tags=("lastpatterntext%d" % (row), "lastpatterntext"), font=font, anchor="e")
			self.drawRow(row)
		self.playCanvas.create_text(0 * self.columnWidth, PLAYHEAD_HEIGHT / 2, text="%d"%(self.colOffset), tags=("timetext"), anchor="w", fill=CELL_FOREGROUND)

		if clearGrid:
			for clock in range(self.horizontalZoom):
				self.gridCanvas.tag_lower("clock%d"%clock)

	# Function to update selectedCell
	#	clock: Clock (column) of selected cell (Optional - default to reselect current column)
	#	track: Track number of selected cell (Optional - default to reselect current =row) 
Example #8
Source File: finalTK.py    From Pytorch-Handwritten-Mathematical-Expression-Recognition with MIT License 6 votes vote down vote up
def choosepic():
	global Flag
	path_=askopenfilename()
	path.set(path_)
	global img_open
	img_open = Image.open(e1.get()).convert('L')
	img=ImageTk.PhotoImage(img_open)
	l1.config(image=img)
	l1.image=img #keep a reference
	var = tkinter.StringVar()
	var.set('                                                                               ')
	e2=Label(root,textvariable = var, font = ('Arial', 25))
	e2.place(relx=0.05,y=500)
	e3=Label(root,textvariable = var, font = ('Arial', 25))
	e3.place(relx=0.55,y=500)
	Flag = False 
Example #9
Source File: box.py    From synthesizer with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self):
        super().__init__()
        self.config_location = appdirs.user_data_dir("PythonJukebox", "Razorvine")
        os.makedirs(self.config_location, mode=0o700, exist_ok=True)
        for family in tk.font.names():
            font = tk.font.nametofont(family)
            font["size"] = abs(font["size"]) + 1
            if family != "TkFixedFont":
                font["family"] = "helvetica"
        self.title("Jukebox   |   synthplayer lib v" + synthplayer.__version__)
        f = ttk.Frame()
        f1 = ttk.Frame(f)
        self.firstTrackFrame = TrackFrame(f1, "Track 1")
        self.secondTrackFrame = TrackFrame(f1, "Track 2")
        self.levelmeterFrame = LevelmeterFrame(f1)
        self.playlistFrame = PlaylistFrame(self, f1)
        self.firstTrackFrame.pack(side=tk.LEFT, fill=tk.Y)
        self.secondTrackFrame.pack(side=tk.LEFT, fill=tk.Y)
        self.levelmeterFrame.pack(side=tk.LEFT, fill=tk.Y)
        self.playlistFrame.pack(side=tk.LEFT, fill=tk.Y)
        f1.pack(side=tk.TOP)
        f2 = ttk.Frame(f)
        self.searchFrame = SearchFrame(self, f2)
        self.searchFrame.pack()
        f2.pack(side=tk.TOP)
        f3 = ttk.Frame(f)
        optionsFrame = ttk.Frame(f3)
        ttk.Button(optionsFrame, text="Database Config", command=self.do_database_config).pack()
        optionsFrame.pack(side=tk.LEFT)
        self.effectsFrame = EffectsFrame(self, f3)
        self.effectsFrame.pack()
        f3.pack(side=tk.TOP)
        self.statusbar = ttk.Label(f, text="<status>", relief=tk.GROOVE, anchor=tk.CENTER)
        self.statusbar.pack(fill=tk.X, expand=True)
        f.pack()
        self.player = Player(self, (self.firstTrackFrame, self.secondTrackFrame))
        self.backend = None
        self.backend_process = None
        self.show_status("Connecting to backend file service...")
        self.after(500, self.connect_backend) 
Example #10
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def symbolsheet(size=20):
        """
        Open a new Tkinter window that displays the entire alphabet
        for the symbol font.  This is useful for constructing the
        ``SymbolWidget.SYMBOLS`` dictionary.
        """
        top = Tk()
        def destroy(e, top=top): top.destroy()
        top.bind('q', destroy)
        Button(top, text='Quit', command=top.destroy).pack(side='bottom')
        text = Text(top, font=('helvetica', -size), width=20, height=30)
        text.pack(side='left')
        sb=Scrollbar(top, command=text.yview)
        text['yscrollcommand']=sb.set
        sb.pack(side='right', fill='y')
        text.tag_config('symbol', font=('symbol', -size))
        for i in range(256):
            if i in (0,10): continue # null and newline
            for k,v in list(SymbolWidget.SYMBOLS.items()):
                if v == chr(i):
                    text.insert('end', '%-10s\t' % k)
                    break
            else:
                text.insert('end', '%-10d  \t' % i)
            text.insert('end', '[%s]\n' % chr(i), 'symbol')
        top.mainloop() 
Example #11
Source File: components.py    From SEM with MIT License 5 votes vote down vote up
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) 
Example #12
Source File: finalTK.py    From Pytorch-Handwritten-Mathematical-Expression-Recognition with MIT License 5 votes vote down vote up
def trans1():
	global img_open
	global prediction, attention
	if Flag:

		print (messagebox.showerror(title='Error', message='No Image'))
	else:

		img_open2 = torch.from_numpy(np.array(img_open)).type(torch.FloatTensor)
		img_open2 = img_open2/255.0
		img_open2 = img_open2.unsqueeze(0)
		img_open2 = img_open2.unsqueeze(0)
		var = tkinter.StringVar()
		var.set('Detecting...')
		e2=Label(root,textvariable = var, font = ('Arial', 25))
		e2.place(relx=0.05,y=500)
		e2.update()
		attention, prediction = for_test(img_open2)
		global prediction_string
		prediction_string = ''
		print(prediction_string)
		
		img_open = np.array(img_open)

		for i in range(attention.shape[0]):
			if prediction[i] == '<eol>':
				continue
			else:
				prediction_string = prediction_string + prediction[i]
		print(prediction_string)
		var.set(prediction_string)
		e2=Label(root,textvariable = var, font = ('Arial', 25))
		e2.place(relx=0.05,y=500)
		image_file = ImageTk.PhotoImage(img_open)
		l1.config(image=image_file)
		l1.image=image_file 
		l1.update() 
Example #13
Source File: UICommon.py    From RaspberryPiBarcodeScanner with MIT License 5 votes vote down vote up
def table_cell(self, cellframe = None, celltext = None, image=None, wraplength=0, justify=tk.LEFT, row=0, column=0, rowspan=1, columnspan=1, sticky=tk.N+tk.S+tk.E+tk.W):
        #
        # create a table cell frame and label and add it to a grid
        #
        cell = tk.Frame(cellframe, bg=Config.style_row_background_colour, highlightthickness=Config.style_row_border_width, highlightbackground=Config.style_row_border_colour)
        label = tk.Label(cell, text=celltext,wraplength=wraplength, image=image, justify=justify,background=Config.style_row_background_colour, foreground=Config.style_row_foreground_colour, padx=5, pady=10,  font=Config.style_row_font)
        label.pack(side=tk.LEFT, fill=tk.Y)
        cell.grid(row=row, column=column, sticky=sticky, rowspan=rowspan, columnspan=columnspan)
        return cell 
Example #14
Source File: UICommon.py    From RaspberryPiBarcodeScanner with MIT License 5 votes vote down vote up
def table_title(self, cellframe, celltext, wraplength=0, justify=tk.LEFT, row=0, column=0, rowspan=1, columnspan=1, sticky=tk.N+tk.S+tk.E+tk.W):
        #
        # create a table title frame and label and add it to a grid
        #
        cell = tk.Frame(cellframe, bg=Config.style_header_background_colour, highlightthickness=Config.style_header_border_width, highlightbackground=Config.style_header_border_colour)
        label = tk.Label(cell, text=celltext,wraplength=wraplength, justify=justify,background=Config.style_header_background_colour, foreground=Config.style_header_foreground_colour, padx=5, pady=10,  font=Config.style_row_font)
        label.pack(side=tk.LEFT, fill=tk.Y)
        cell.grid(row=row, column=column, sticky=sticky, rowspan=rowspan, columnspan=columnspan)
        return cell 
Example #15
Source File: UICommon.py    From RaspberryPiBarcodeScanner with MIT License 5 votes vote down vote up
def message_box(self, master, title, content, target=None):
        #
        # replaces the standard tkinter message box
        #
        box = tk.Frame(master, highlightbackground="grey", highlightcolor="grey", highlightthickness=1, background="#FFFFFF")
        tk.Label(box, text=title, font="DejaVuSans 22 bold", background="#FFFFFF", pady=20).pack()
        tk.Label(box, text=content, font="DejaVuSans 22 normal", background="#FFFFFF", pady=30).pack()
        tk.Button(box, text="Close", font="DejaVuSans 28 normal",pady=20, command=lambda arg1=box, arg2=target: self.__message_box_close(arg1, arg2)).pack(side = tk.BOTTOM, fill=tk.X)
        box.place(x = 20, y=100, width=280) 
Example #16
Source File: chunkparser_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def _init_fonts(self, top):
        # TWhat's our font size (default=same as sysfont)
        self._size = IntVar(top)
        self._size.set(20)
        self._font = tkinter.font.Font(family='helvetica',
                                 size=-self._size.get())
        self._smallfont = tkinter.font.Font(family='helvetica',
                                      size=-(int(self._size.get()*14/20))) 
Example #17
Source File: run_gui.py    From margipose with Apache License 2.0 5 votes vote down vote up
def _make_global_toolbar(self, master):
        toolbar = tk.Frame(master, bd=1, relief=tk.RAISED)

        def add_label(text):
            opts = dict(text=text) if isinstance(text, str) else dict(textvariable=text)
            label = tk.Label(toolbar, **opts)
            label.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2)
            return label

        add_label('Example index:')
        txt_cur_example = tk.Spinbox(
            toolbar, textvariable=self.var_cur_example, command=self.on_change_example,
            wrap=True, from_=0, to=len(self.dataset) - 1, font=tk.font.Font(size=12))
        def on_key_cur_example(event):
            if event.keysym == 'Return':
                self.on_change_example()
        txt_cur_example.bind('<Key>', on_key_cur_example)
        txt_cur_example.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2)

        if self.model is not None:
            add_label('MPJPE:')
            add_label(self.var_mpjpe)
            add_label('PCK@150mm:')
            add_label(self.var_pck)

            chk_aligned = tk.Checkbutton(
                toolbar, text='Procrustes alignment', variable=self.var_aligned,
                command=lambda: self.update_current_tab())
            chk_aligned.pack(side=tk.LEFT, fill=tk.Y, padx=2, pady=2)

        return toolbar 
Example #18
Source File: zynthian_gui_songeditor.py    From zynthian-ui with GNU General Public License v3.0 5 votes vote down vote up
def updateCellSize(self):
		self.rowHeight = (self.gridHeight - 2) / self.verticalZoom
		self.columnWidth = self.gridWidth / self.horizontalZoom
		self.fontsize = int(self.rowHeight * 0.5)
		if self.fontsize > 20:
			self.fontsize = 20 # Ugly font scale limiting

	# Function to clear a pattern 
Example #19
Source File: finalTK.py    From Pytorch-Handwritten-Mathematical-Expression-Recognition with MIT License 5 votes vote down vote up
def trans():
	global img_open
	global prediction, attention
	var = tkinter.StringVar()
	var.set('                                                                               ')
	e3=Label(root,textvariable = var, font = ('Arial', 25))
	e3.place(relx=0.55,y=500)
	if Flag:
		print (messagebox.showerror(title='Error', message='No Image'))

	else:
		img_open2 = torch.from_numpy(np.array(img_open)).type(torch.FloatTensor)
		img_open2 = img_open2/255.0
		img_open2 = img_open2.unsqueeze(0)
		img_open2 = img_open2.unsqueeze(0)
		attention, prediction = for_test(img_open2)
		global prediction_string
		prediction_string = ''
		print(prediction_string)
		var = tkinter.StringVar()
		img_open = np.array(img_open)

		for i in range(attention.shape[0]):
			print(i)
			if prediction[i] == '<eol>':
				continue
			else:
				prediction_string = prediction_string + prediction[i]
			print(prediction_string)
			var.set(prediction_string)
			e3=Label(root,textvariable = var, font = ('Arial', 25))
			e3.place(relx=0.55,y=500)
			attention2 = imresize(attention[i,0,:,:],(img_open.shape[1],img_open.shape[0]))
			attention2 = attention2*attention2
			image_attention = img_open + attention2 * 1000
			image_open2 = Image.fromarray(image_attention)
			image_file = ImageTk.PhotoImage(image_open2)
			l2.config(image=image_file)
			l2.image=image_file #keep a reference
			l2.update()
			l2.after(500) 
Example #20
Source File: gui.py    From synthesizer with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, audio):
        super().__init__()
        self.audio = audio
        self.wm_title("DrumKit")
        self.buttongrid = ButtonGrid(self, self.audio)
        self.buttongrid.pack()
        self.messages = tkinter.Text(self, height=4, font=tkinter.font.Font(size=12), padx=10, pady=10)
        self.messages.pack(fill=tkinter.X)
        self.audio = None
        for b in self.buttongrid.buttons:
            self.bind(b.hotkey, lambda e, b=b: self.buttongrid.hotkeyed(e, b))
        sys.stdout = StdoutAdapter(self.messages) 
Example #21
Source File: mainwindow_ui.py    From pydiff with MIT License 5 votes vote down vote up
def create_text_areas(self):
        self.leftFileTextArea = Text(self.main_window, padx=5, pady=5, width=1, height=1, bg=self.grayColor)
        self.leftFileTextArea.grid(row=self.textAreasRow, column=self.leftTextAreaCol, sticky=NSEW)
        self.leftFileTextArea.config(font=self.text_area_font)
        self.leftFileTextArea.config(wrap='none')

        self.rightFileTextArea = Text(self.main_window, padx=5, pady=5, width=1, height=1, bg=self.grayColor)
        self.rightFileTextArea.grid(row=self.textAreasRow, column=self.rightTextAreaCol, sticky=NSEW)
        self.rightFileTextArea.config(font=self.text_area_font)
        self.rightFileTextArea.config(wrap='none')

        # configuring highlight tags
        self.leftFileTextArea.tag_configure('red', background=self.redColor)
        self.leftFileTextArea.tag_configure('darkred', background=self.darkredColor)
        self.leftFileTextArea.tag_configure('gray', background=self.grayColor)
        self.leftFileTextArea.tag_configure('search', background=self.darkYellowColor)
        self.rightFileTextArea.tag_configure('green', background=self.greenColor)
        self.rightFileTextArea.tag_configure('darkgreen', background=self.darkgreenColor)
        self.rightFileTextArea.tag_configure('gray', background=self.grayColor)
        self.rightFileTextArea.tag_configure('search', background=self.darkYellowColor)
        self.rightFileTextArea.tag_configure('purpleLight', background=self.purpleLight)

        # disable the text areas
        self.leftFileTextArea.config(state=DISABLED)
        self.rightFileTextArea.config(state=DISABLED)

    # Line numbers 
Example #22
Source File: zynthian_gui_seqtrigger.py    From zynthian-ui with GNU General Public License v3.0 5 votes vote down vote up
def drawCell(self, col, row, clear = False):
		pad = row + col * self.rows + 1 # Index pads from 1 and use index to map sequence (sequence 0 is used by pattern editor)
		if col < 0 or col >= self.columns or row < 0 or row >= self.rows:
			return
		padX = col * self.width / self.columns
		padY = row * self.height / self.rows
		padWidth = self.width / self.columns - 2 #TODO: Calculate pad size once
		padHeight = self.height / self.rows - 2
		cell = self.gridCanvas.find_withtag("pad:%d"%(pad))
		if cell:
			if self.parent.libseq.getPlayState(pad) == zynthian_gui_config.SEQ_STOPPED:
				playColour = self.padColoursStopped[self.parent.libseq.getPlayMode(pad)]
			elif self.parent.libseq.getPlayState(pad) == zynthian_gui_config.SEQ_STARTING:
				playColour = self.padColoursStarting[self.parent.libseq.getPlayMode(pad)]
			elif self.parent.libseq.getPlayState(pad) == zynthian_gui_config.SEQ_STOPPING:
				playColour = self.padColoursStopping[self.parent.libseq.getPlayMode(pad)]
			else:
				playColour = self.padColoursPlaying[self.parent.libseq.getPlayMode(pad)]
			self.gridCanvas.itemconfig(cell, fill=playColour)
			self.gridCanvas.coords(cell, padX, padY, padX + padWidth, padY + padHeight)
		else:
			cell = self.gridCanvas.create_rectangle(padX, padY, padX + padWidth, padY + padHeight,
				fill='grey', width=0, tags=("pad:%d"%(pad), "gridcell"))
			self.gridCanvas.create_text(padX + padWidth / 2, padY + padHeight / 2,
				font=tkFont.Font(family=zynthian_gui_config.font_topbar[0],
				size=int(padHeight * 0.3)),
				fill=zynthian_gui_config.color_panel_tx,
				tags="lbl_pad:%d"%(pad),
				text="%s%d" % (chr(col + 65), row + 1))
			self.gridCanvas.tag_bind("pad:%d"%(pad), '<Button-1>', self.onPadPress)
			self.gridCanvas.tag_bind("lbl_pad:%d"%(pad), '<Button-1>', self.onPadPress)
			self.gridCanvas.tag_bind("pad:%d"%(pad), '<ButtonRelease-1>', self.onPadRelease)
			self.gridCanvas.tag_bind("lbl_pad:%d"%(pad), '<ButtonRelease-1>', self.onPadRelease)

	# Function to draw pad
	#	pad: Pad index
	#	returns: Pad sequence play state 
Example #23
Source File: zynthian_gui_patterneditor.py    From zynthian-ui with GNU General Public License v3.0 5 votes vote down vote up
def drawGrid(self, clearGrid = False):
		font = tkFont.Font(family=zynthian_gui_config.font_topbar[0], size=self.fontsize)
		if clearGrid:
			self.gridCanvas.delete(tkinter.ALL)
			self.stepWidth = (self.gridWidth - 2) / self.parent.libseq.getSteps()
			self.drawPianoroll()
		# Draw cells of grid
		self.gridCanvas.itemconfig("gridcell", fill="black")
		# Redraw gridlines
		self.gridCanvas.delete("gridline")
		if self.parent.libseq.getStepsPerBeat():
			for step in range(0, self.parent.libseq.getSteps() + 1, self.parent.libseq.getStepsPerBeat()):
				self.gridCanvas.create_line(step * self.stepWidth, 0, step * self.stepWidth, self.zoom * self.rowHeight - 1, fill=GRID_LINE, tags=("gridline"))
		# Delete existing note names
		self.pianoRoll.delete("notename")
		for note in range(self.keyOrigin, self.keyOrigin + self.zoom):
			# Update pianoroll keys
			key = note % 12
			row = note - self.keyOrigin
			self.drawRow(note)
			if clearGrid:
				# Create last note labels in grid
				self.gridCanvas.create_text(self.gridWidth - self.selectThickness, self.fontsize, state="hidden", tags=("lastnotetext%d" % (row), "lastnotetext"), font=font, anchor="e")
			id = "row%d" % (row)
			if key in (0,2,4,5,7,9,11):
				self.pianoRoll.itemconfig(id, fill="white")
				if key == 0:
					self.pianoRoll.create_text((self.pianoRollWidth / 2, self.rowHeight * (self.zoom - row - 0.5)), text="C%d (%d)" % ((self.keyOrigin + row) // 12 - 1, self.keyOrigin + row), font=font, fill=CANVAS_BACKGROUND, tags="notename")
					self.gridCanvas.create_line(0, (self.zoom - row) * self.rowHeight, self.gridWidth, (self.zoom - row) * self.rowHeight, fill=GRID_LINE, tags=("gridline"))
			else:
				self.pianoRoll.itemconfig(id, fill="black")
		# Set z-order to allow duration to show
		if clearGrid:
			for step in range(self.parent.libseq.getSteps()):
				self.gridCanvas.tag_lower("step%d"%step)
		self.gridCanvas.tag_raise("selection")

	# Function to draw pianoroll keys (does not fill key colour) 
Example #24
Source File: Terminal.py    From spartacus with GNU General Public License v2.0 5 votes vote down vote up
def _displayLoop(self):
        """
        This is the display loop. This is in charge of asynchronous display operations and is
        launched right after device initialisation is over.
        :return:
        """
        self.window = tkinter.Tk()
        self.window.title("Spartacus Learning VM")
        self.window.bind("<KeyPress>", self._keyDown)
        self.customFont = tkinter.font.Font(family="Courier", size=DISPLAY_FONT_SIZE)
        self.displayWindow = tkinter.Label(self.window,
                                           text=self._generateDisplayText(),
                                           font=self.customFont,
                                           bg="black",
                                           fg="white",
                                           justify=tkinter.LEFT)
        self.displayWindow.grid()

        while True:
            if self._shutdownProcedureInAction:
                # This allows the method to return if we need to shutdown the system
                self.window.quit()
                break
            self.displayWindow.config(text=self._generateDisplayText())
            #TODO need more research on this
            self.window.update_idletasks()
            self.window.update()
            time.sleep(self._displayRefreshRate) 
Example #25
Source File: zynthian_gui_patterneditor.py    From zynthian-ui with GNU General Public License v3.0 5 votes vote down vote up
def updateRowHeight(self):
		self.rowHeight = (self.gridHeight - 2) / self.zoom
		self.fontsize = int(self.rowHeight * 0.5)
		if self.fontsize > 20:
			self.fontsize = 20 # Ugly font scale limiting

	# Function to clear a pattern 
Example #26
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def __setitem__(self, attr, value):
        if attr in ('color', 'font', 'justify', 'width'):
            if attr == 'color': attr = 'fill'
            self.canvas().itemconfig(self._tag, {attr:value})
        else:
            CanvasWidget.__setitem__(self, attr, value) 
Example #27
Source File: rdparser_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def _init_grammar(self, parent):
        # Grammar view.
        self._prodframe = listframe = Frame(parent)
        self._prodframe.pack(fill='both', side='left', padx=2)
        self._prodlist_label = Label(self._prodframe, font=self._boldfont,
                                     text='Available Expansions')
        self._prodlist_label.pack()
        self._prodlist = Listbox(self._prodframe, selectmode='single',
                                 relief='groove', background='white',
                                 foreground='#909090', font=self._font,
                                 selectforeground='#004040',
                                 selectbackground='#c0f0c0')

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

        self._productions = list(self._parser.grammar().productions())
        for production in self._productions:
            self._prodlist.insert('end', ('  %s' % production))
        self._prodlist.config(height=min(len(self._productions), 25))

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

        # If they select a production, apply it.
        self._prodlist.bind('<<ListboxSelect>>', self._prodlist_select) 
Example #28
Source File: rdparser_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def _init_feedback(self, parent):
        self._feedbackframe = feedbackframe = Frame(parent)
        feedbackframe.pack(fill='x', side='bottom', padx=3, pady=3)
        self._lastoper_label = Label(feedbackframe, text='Last Operation:',
                                     font=self._font)
        self._lastoper_label.pack(side='left')
        lastoperframe = Frame(feedbackframe, relief='sunken', border=1)
        lastoperframe.pack(fill='x', side='right', expand=1, padx=5)
        self._lastoper1 = Label(lastoperframe, foreground='#007070',
                                background='#f0f0f0', font=self._font)
        self._lastoper2 = Label(lastoperframe, anchor='w', width=30,
                                foreground='#004040', background='#f0f0f0',
                                font=self._font)
        self._lastoper1.pack(side='left')
        self._lastoper2.pack(side='left', fill='x', expand=1) 
Example #29
Source File: rdparser_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def _redraw(self):
        canvas = self._canvas

        # Delete the old tree, widgets, etc.
        if self._tree is not None:
            self._cframe.destroy_widget(self._tree)
        for twidget in self._textwidgets:
            self._cframe.destroy_widget(twidget)
        if self._textline is not None:
            self._canvas.delete(self._textline)

        # Draw the tree.
        helv = ('helvetica', -self._size.get())
        bold = ('helvetica', -self._size.get(), 'bold')
        attribs = {'tree_color': '#000000', 'tree_width': 2,
                   'node_font': bold, 'leaf_font': helv,}
        tree = self._parser.tree()
        self._tree = tree_to_treesegment(canvas, tree, **attribs)
        self._cframe.add_widget(self._tree, 30, 5)

        # Draw the text.
        helv = ('helvetica', -self._size.get())
        bottom = y = self._cframe.scrollregion()[3]
        self._textwidgets = [TextWidget(canvas, word, font=self._font)
                             for word in self._sent]
        for twidget in self._textwidgets:
            self._cframe.add_widget(twidget, 0, 0)
            twidget.move(0, bottom-twidget.bbox()[3]-5)
            y = min(y, twidget.bbox()[1])

        # Draw a line over the text, to separate it from the tree.
        self._textline = canvas.create_line(-5000, y-5, 5000, y-5, dash='.')

        # Highlight appropriate nodes.
        self._highlight_nodes()
        self._highlight_prodlist()

        # Make sure the text lines up.
        self._position_text() 
Example #30
Source File: rdparser_app.py    From razzy-spinner with GNU General Public License v3.0 5 votes vote down vote up
def help(self, *e):
        self._autostep = 0
        # The default font's not very legible; try using 'fixed' instead.
        try:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75, font='fixed')
        except:
            ShowText(self._top, 'Help: Recursive Descent Parser Application',
                     (__doc__ or '').strip(), width=75)