def test_families(self): families = font.families(self.root) self.assertIsInstance(families, tuple) self.assertTrue(families) for family in families: self.assertIsInstance(family, str) self.assertTrue(family)
def FindFont(self, families, size): fontfamilies = tkfont.families() print(fontfamilies) for family in families: if family in fontfamilies: return tkfont.Font(family=family, size=size) return None
def findfont(self, names): "Return name of first font family derived from names." for name in names: if name.lower() in (x.lower() for x in tkfont.names(root=self)): font = tkfont.Font(name=name, exists=True, root=self) return font.actual()["family"] elif name.lower() in (x.lower() for x in tkfont.families(root=self)): return name
def body( self, master ): theRow = 0 Tix.Label( master, text="Font Family" ).grid( row=theRow, column=0 ) Tix.Label( master, text="Font Size" ).grid( row=theRow, column=2 ) theRow += 1 # Font Families fontList = Tix.ComboBox( master, command=self.selectionChanged, dropdown=False, editable=False, selectmode=Tix.IMMEDIATE, variable=self._family ) fontList.grid( row=theRow, column=0, columnspan=2, sticky=Tix.N+Tix.S+Tix.E+Tix.W, padx=10 ) first = None familyList = list(tkFont.families( )) familyList.sort() for family in familyList: if family[0] == '@': continue if first is None: first = family fontList.insert( Tix.END, family ) fontList.configure( value=first ) # Font Sizes sizeList = Tix.ComboBox( master, command=self.selectionChanged, dropdown=False, editable=False, selectmode=Tix.IMMEDIATE, variable=self._sizeString ) sizeList.grid( row=theRow, column=2, columnspan=2, sticky=Tix.N+Tix.S+Tix.E+Tix.W, padx=10 ) for size in range( 6,31 ): sizeList.insert( Tix.END, '%d' % size ) sizeList.configure( value='9' ) # Styles if self._showStyles is not None: theRow += 1 if self._showStyles in ( FontChooser.ALL, FontChooser.BASIC ): Tix.Label( master, text='Styles', anchor=Tix.W ).grid( row=theRow, column=0, pady=10, sticky=Tix.W ) theRow += 1 Tix.Checkbutton( master, text="bold", command=self.selectionChanged, offvalue='normal', onvalue='bold', variable=self._weight ).grid(row=theRow, column=0) Tix.Checkbutton( master, text="italic", command=self.selectionChanged, offvalue='roman', onvalue='italic', variable=self._slant ).grid(row=theRow, column=1) if self._showStyles == FontChooser.ALL: Tix.Checkbutton( master, text="underline", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isUnderline ).grid(row=theRow, column=2) Tix.Checkbutton( master, text="overstrike", command=self.selectionChanged, offvalue=False, onvalue=True, variable=self._isOverstrike ).grid(row=theRow, column=3) # Sample Text theRow += 1 Tix.Label( master, text='Sample Text', anchor=Tix.W ).grid( row=theRow, column=0, pady=10, sticky=Tix.W ) theRow += 1 self.sampleText = Tix.Text( master, height=11, width=70 ) self.sampleText.insert( Tix.INSERT, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ\nabcdefghijklmnopqrstuvwxyz', 'fontStyle' ) self.sampleText.config( state=Tix.DISABLED ) self.sampleText.tag_config( 'fontStyle', font=self._currentFont ) self.sampleText.grid( row=theRow, column=0, columnspan=4, padx=10 )
def createMenu(self): """Create the menu widget. It is rather long and messy to add all of the options, so it is split into functions.""" self.menu = tk.Menu(master=self,takefocus=False) self.menu.add_cascade(label="File", menu=menus.createFileMenu(self.menu)) self.menu.add_cascade(label="Edit", menu=menus.createEditMenu(self.menu)) self.menu.add_cascade(label="Options", menu=menus.createOptionsMenu(self.menu, self.controlSize,self.controlType,font.families()))
def _add_toolbar(self, parent): # add a toolbar (must be in a frame) toolbar = Frame(parent) if self.__tbDocked: # only create a tear off if the toolbar is being docked tearoff = Frame(toolbar, cursor='fleur', borderwidth=2, relief=RAISED) # use a label as a 'grip' to tearoff toolbar # rather than the vertical scrollbars used in the # original Tcl demo self.__gripImg = BitmapImage(file='images\\gray25.xbm') grip = ttk.Label(tearoff, image=self.__gripImg) grip.pack(side=LEFT, fill=Y) tearoff.pack(side=LEFT) toolbar.__tearoff = tearoff # bind the 'tearoff grip' to capture dragging grip.bind('<ButtonPress-1>', self._start_tear) grip.bind('<ButtonRelease-1>', self._tear_off) # create the toolbar widgets contents = ttk.Frame(toolbar) btn = ttk.Button(contents, text='Button', style='Demo.Toolbutton', command=lambda: self.txt.insert(END, 'Button pressed.\n')) btn.pack(side=LEFT) cb = ttk.Checkbutton(contents, text='Check', style='Demo.Toolbutton') cb['command'] = lambda c=cb: self._say_check(c) cb.pack(side=LEFT) menu = Menu(contents) mb = ttk.Menubutton(contents, text='Menu', menu=menu) menu.add_command(label='Just', command=lambda: self.txt.insert(END, 'Just\n')) menu.add_command(label='An', command=lambda: self.txt.insert(END, 'An\n')) menu.add_command(label='Example', command=lambda: self.txt.insert(END, 'Example\n')) mb.pack(side=LEFT) combo = ttk.Combobox(contents, value=sorted(font.families()), state='readonly') combo.bind('<<ComboboxSelected>>', lambda e, v=combo: self._change_font(e, v.get())) combo.pack(side=LEFT) contents.pack(side=LEFT) return toolbar
def __init__(self, parent, value): available_families = sorted(list(tkFont.families())) available_families.insert(-1, '') for fnt in data.always_available_fonts: available_families.insert(1, fnt) if not value in available_families: v = '' else: v = value Pmw.ScrolledListBox.__init__( self, parent, labelpos = 'nw', label_text = _('Font family'), listbox_selectmode = 'single', items = available_families, hull_relief = 'ridge') self.select_set( available_families.index( v)) self.see( available_families.index( v))
def main(package_name): if os.name == 'posix': head, tail = os.path.split(sys.executable) pip_path = '' if '3' in tail: pip_path = head + '/pip3' else: pip_path = head + '/pip' if not os.path.exists(pip_path): import packages_linux packages_linux.pip() python_path = sys.executable.replace('pythonw', 'python') root = Tk() if 'DejaVu Sans' in list(font.families()): police = font.Font(family='DejaVu Sans', size=10) root.option_add('*Font', police) Label(root, text='Ce programme a besoin d\u2019installer ' + package_name + ' pour fonctionner.', width=50).grid(column=0, row=0) bouton_maj = Button( root, text='Installer ' + package_name, command=lambda: [ os.system(python_path + ' -m pip install --upgrade ' + package_name + ' --user'), os.execl(sys.executable, sys.executable, *sys.argv) ]) bouton_maj.grid(column=0, row=1) bouton_fermer = Button(root, text='Ne pas installer ' + package_name, command=quit) bouton_fermer.grid(column=0, row=2) root.title(package_name) root.resizable(width=False, height=False) if os.name == 'nt': import ctypes import prgm ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID( 'equations') img = PhotoImage(file='package.png') root.tk.call('wm', 'iconphoto', root._w, img) root.mainloop()
def __init__(self, master=None, callback=None, **kwargs): """ Create a FontFamilyListbox. :param master: master widget :type master: widget :param callback: callable object with one argument: the font family name :type callback: function :param kwargs: keyword arguments passed to :class:`~ttkwidgets.ScrolledListbox`, in turn passed to :class:`tk.Listbox` """ ScrolledListbox.__init__(self, master, compound=tk.RIGHT, **kwargs) self._callback = callback font_names = sorted(set(font.families())) index = 0 self.font_indexes = {} for name in font_names: self.listbox.insert(index, name) self.font_indexes[index] = name index += 1 self.listbox.bind("<<ListboxSelect>>", self._on_click)
def openSettingsWindow(self): settingsWindow = tkinter.Toplevel(self.root) settingsWindow.title("Settings") settingsWindow.geometry("200x400") scrollbar = tkinter.Scrollbar(settingsWindow) scrollbar.pack(side=tkinter.RIGHT, fill=tkinter.Y) fontList = tkinter.Listbox(settingsWindow, selectmode=tkinter.SINGLE, yscrollcommand=scrollbar.set) scrollbar.configure(command=fontList.yview) index = 0 oldFonts = font.families() fonts = [] for option in oldFonts: if option[0] != '@': fonts.append(option) for option in fonts: fontList.insert(index, option) index += 1 selectButton = tkinter.Button(settingsWindow, text="Select this font", command=lambda: self.setFont(str(fonts[fontList.curselection()[0]]))) fontList.pack(fill=tkinter.BOTH, expand=1) selectButton.pack()
def def_gui(self): """Define the GUI""" self.main_text_input = JKTextyExtraText(self.root) self.main_text_input.config(font=("Helvetica", 12, "normal")) self.main_text_input.bind("<space>", self._highlight_keywords) self.main_text_input.insert(1.0, self._ASAO_info()) self.save_button = ttk.Button(self.root, text='Save', command=lambda: self._save()) self.open_button = ttk.Button(self.root, text='Open', command=lambda: self._open()) self.quit_button = ttk.Button(self.root, text='Quit', command=lambda: self._quit()) self.settings_button = ttk.Button(self.root, text='Settings', command=lambda: self._settings()) self.font_frame = ttk.Labelframe(self.root, text='Font Options') self.font_combo = ttk.Combobox(self.font_frame, values=font.families()) self.font_button = ttk.Button(self.font_frame, text='Change Font', command=lambda: self._change_font()) try: self.font_size = ttk.Spinbox(self.font_frame, from_=1, to=100) except: # Older tkinter version self.font_size = tk.Spinbox(self.font_frame, from_=1, to=100) mbox.showwarning('Warning', 'You are using an older version of Tkinter. It is suggested that you update Tkinter, but if you don\'t feel like it, you can continue using Texty, just some of the features may not work right.', parent=self.root) self.font_opt = ttk.Combobox(self.font_frame, values=('normal', 'bold', 'italic', 'bold italic'))
def get_clean_fonts(): """ Return a sane list of fonts for the system that has both regular and bold variants. Pre-pend "default" to the beginning of the list. Returns ------- list: A list of valid fonts for the system """ fmanager = font_manager.FontManager() fonts = dict() for font in fmanager.ttflist: if str(font.weight) in ("400", "normal", "regular"): fonts.setdefault(font.name, dict())["regular"] = True if str(font.weight) in ("700", "bold"): fonts.setdefault(font.name, dict())["bold"] = True valid_fonts = {key for key, val in fonts.items() if len(val) == 2} retval = sorted(list(valid_fonts.intersection(tk_font.families()))) return ["default"] + retval
def step_callback(self): if self.sheep_left_check(): self.canvas.delete("all") self.wolf.update() for sheep in self.wolf.sheep_list: sheep.update() self.render_wolf() self.render_sheep() else: print(TkFont.families()) font = TkFont.Font(size=20) end_window = Tk() end_window.title("Error") end_window.geometry("250x30") label = Message(end_window, font=font, text="All sheep are dead, can't step", width=1000) label.pack() end_window.mainloop()
def font_change(self): top = tk.Toplevel(self) top.title("Select Font") top.geometry("250x350") textfont = font.Font(family='arial') self.editor.config(font=textfont) fc = tk.Listbox(top) fc.pack(side=tk.LEFT, fill=tk.BOTH, expand=True) for f in font.families(): fc.insert('end', f) fc.bind('<ButtonRelease-1>', lambda e: textfont.config(family=fc.get(fc.curselection()))) vsb = tk.Scrollbar(top) vsb.pack(side=tk.RIGHT, fill=tk.Y) fc.configure(yscrollcommand=vsb.set) vsb.configure(command=fc.yview)
def __createFontFamilyCombobox(self): self.var_fontfamily = tk.StringVar() self.var_fontfamily.trace_add("write", self.__FontChange) # 创建字体的下拉菜单 fontfamily_combobox = ttk.Combobox(self.element_frame, textvariable=self.var_fontfamily) fontfamily_combobox['state'] = "readonly" # 获取当前系统中所有的字体,并筛选出首字母是中文的字体 list_families = [] for i in font.families(): if '\u4e00' <= i[0] <= '\u9fff': list_families.append(i) self.families = tuple(list_families) fontfamily_combobox['value'] = self.families # 默认选用 微软雅黑字体 try: currentindex = self.families.index("微软雅黑") except: currentindex = 0 fontfamily_combobox.current(currentindex) return fontfamily_combobox
def window(self): self.root.title("Font Picker") self.root.geometry("250x85") self.root.resizable(False, False) self.root.protocol("WM_DELETE_WINDOW", self.Close_Win) available_fonts = list(font.families()) available_fonts.sort() self.choose_font.config(width=20, textvariable=self.selected_font, values=available_fonts) self.choose_font.current(31) self.choose_font.pack(fill=BOTH, expand=1, padx=20, pady=10) # self.choose_font.bind("<Key>", lambda: self.FontSearch()) # Added *args to compensate, yet still removed statement due to unexpected behaviour self.FontSearch() Button(self.root, text='Ok', width=5, command=self.Ok).pack(side=RIGHT, padx=(5, 10), pady=5) Button(self.root, text='Cancel', width=5, command=self.Cancel).pack(side=RIGHT, padx=(10, 5), pady=5)
def __init__(self, root, text): if not isinstance(text, str): raise TypeError("text") super(FontChooserFrame, self).__init__(root, text=text) self._root = root self._fontName = StringVar() self._fontSize = IntVar() self._isBold = BooleanVar() self._isItalic = BooleanVar() ttk.Label(self, text="Шрифт").grid(row=0, column=0, padx=2, pady=2) fonts = list(font.families()) list.sort(fonts) combo = ttk.Combobox(self, values=fonts, textvariable=self._fontName) combo.grid(row=0, column=1, padx=2, pady=2) lbl = ttk.Label(self, text="Размер") lbl.grid(row=0, column=2, padx=2, pady=2) spin = Spinbox(self, from_=1, to=500, increment=1, width=4, textvariable=self._fontSize) spin.grid(row=0, column=3, padx=2, pady=2) chk = ttk.Checkbutton(self, text="Жирный", variable=self._isBold) chk.grid(row=0, column=4, padx=2, pady=2) chk = ttk.Checkbutton(self, text="Наклон", variable=self._isItalic) chk.grid(row=0, column=5, padx=2, pady=2)
def draw_label_options(self): label_frame = ttk.LabelFrame(self.top, text="Label", padding=FRAME_PAD) label_frame.grid(sticky="ew") label_frame.columnconfigure(0, weight=1) entry = ttk.Entry(label_frame, textvariable=self.shape_text) entry.grid(sticky="ew", pady=PADY) # font options frame = ttk.Frame(label_frame) frame.grid(sticky="nsew", pady=PADY) frame.columnconfigure(0, weight=1) frame.columnconfigure(1, weight=1) frame.columnconfigure(2, weight=1) combobox = ttk.Combobox( frame, textvariable=self.font, values=sorted(font.families()), state="readonly", ) combobox.grid(row=0, column=0, sticky="nsew") combobox = ttk.Combobox( frame, textvariable=self.font_size, values=FONT_SIZES, state="readonly" ) combobox.grid(row=0, column=1, padx=PADX, sticky="nsew") button = ttk.Button(frame, text="Color", command=self.choose_text_color) button.grid(row=0, column=2, sticky="nsew") # style options frame = ttk.Frame(label_frame) frame.grid(sticky="ew") for i in range(3): frame.columnconfigure(i, weight=1) button = ttk.Checkbutton(frame, variable=self.bold, text="Bold") button.grid(row=0, column=0, sticky="ew") button = ttk.Checkbutton(frame, variable=self.italic, text="Italic") button.grid(row=0, column=1, padx=PADX, sticky="ew") button = ttk.Checkbutton(frame, variable=self.underline, text="Underline") button.grid(row=0, column=2, sticky="ew")
def __init__(self, master, **kwargs): super().__init__(**kwargs) self.master = master self.transient(self.master) self.geometry('350x250') self.title('Choose font and size') self.configure(bg=self.master.background) self.text_to_font = tk.StringVar() self.text_to_size = tk.StringVar() top_frame = tk.Frame(self, bg=self.master.background) middle_frame = tk.Frame(self, bg=self.master.background) bottom_frame = tk.Frame(self, bg=self.master.background) font_entry_label = ttk.Label(top_frame, text="Font: ", style="editor.TLabel") self.font_comb = ttk.Combobox(top_frame,width=20,textvariable=self.text_to_font) self.text_to_font.set(self.master.font_family) size_entry_label = ttk.Label(middle_frame, text="Size: ", style="editor.TLabel") self.size_input = tk.Spinbox(middle_frame, from_=0, to=99, textvariable=self.text_to_size) self.text_to_size.set(self.master.font_size) self.save_button = ttk.Button(bottom_frame, text="Save", command=self.save, style="editor.TButton") font_entry_label.pack(side=tk.LEFT) size_entry_label.pack(side=tk.LEFT) self.size_input.pack(side=tk.LEFT, fill=tk.X, expand=1) self.font_comb.pack(side=tk.LEFT, fill=tk.X, expand=1) self.save_button.pack(side=tk.BOTTOM, pady=(0, 20)) top_frame.pack(side=tk.TOP, expand=1, fill=tk.X, padx=30) middle_frame.pack(side=tk.TOP, expand=1, fill=tk.X, padx=30) bottom_frame.pack(side=tk.TOP, expand=1, fill=tk.X) self.available_fonts = sorted(families()) self.font_comb['values'] = self.available_fonts
def _init_fonts(self): self.set_default("view.io_font_family", "Courier" if running_on_mac_os() else "Courier New") default_editor_family = "Courier New" families = tk_font.families() for family in ["Consolas", "Ubuntu Mono", "Menlo", "DejaVu Sans Mono"]: if family in families: default_editor_family = family break self.set_default("view.editor_font_family", default_editor_family) self.set_default("view.editor_font_size", 14 if running_on_mac_os() else 11) default_font = tk_font.nametofont("TkDefaultFont") self._fonts = { 'IOFont': tk_font.Font(family=self.get_option("view.io_font_family")), 'EditorFont': tk_font.Font(family=self.get_option("view.editor_font_family")), 'BoldEditorFont': tk_font.Font(family=self.get_option("view.editor_font_family"), weight="bold"), 'ItalicEditorFont': tk_font.Font(family=self.get_option("view.editor_font_family"), slant="italic"), 'BoldItalicEditorFont': tk_font.Font(family=self.get_option("view.editor_font_family"), weight="bold", slant="italic"), 'TreeviewFont': tk_font.Font(family=default_font.cget("family"), size=default_font.cget("size")) } self.update_fonts()
def main(root, text, menubar): objFormat = Format(text) fontoptions = families(root) font = Font(family="Arial", size=10) text.configure(font=font) SettingsManager.setup(objFormat, font) # setup the settings formatMenu = Menu(menubar, tearoff=False) fsubmenu = Menu(formatMenu, tearoff=False) ssubmenu = Menu(formatMenu, tearoff=False) for option in fontoptions: fsubmenu.add_command(label=option, command=lambda option=option: SettingsManager.change_font(font, "font_family", option)) for value in range(1, 31): ssubmenu.add_command(label=str(value), command=lambda value=value: SettingsManager.change_font(font, "font_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)
def test_fontselectframe_family(self): frame = FontSelectFrame(self.window) frame.pack() self.window.update() frame._family_dropdown.set(font.families()[1]) self.window.update() frame._on_family(frame._family_dropdown.get()) results = frame.font self.assertIsInstance(results, tuple) self.assertEqual(len(results), 2) self.assertIsInstance(results[0], tuple) self.assertEqual(len(results[0]), 2) self.assertIsInstance(results[1], font.Font) frame._on_size(20) frame._on_family('Arial') frame._on_properties((True, True, True, True)) self.window.update() results = frame.font self.assertEqual( results[0], ('Arial', 20, 'bold', 'italic', 'underline', 'overstrike'))
def __init__(self, master, data_dict): # Prints all available fonts to stdout print(font.families()) # Choose your font appfont = font.Font(family='Courier New', size=12, weight='bold') # Call superclass constructor tk.Frame.__init__(self, master) # Place frame into main window self.grid() row = 0 for key, val in data_dict.items(): left = tk.Label(self, text=key, font=appfont) mid = tk.Label(self, text=":", font=appfont) right = tk.Label(self, text=val, font=appfont) # sticky=tk.W means stick to the west left.grid(row=row, column=0, sticky=tk.W) mid.grid(row=row, column=1) right.grid(row=row, column=2, sticky=tk.W) row += 1
def def_gui(self): """Define the GUI""" self.main_text_input = JKTextyExtraText(self.root) self.main_text_input.config(font=("Helvetica", 12, "normal")) bold_font = font.Font(self.main_text_input, self.main_text_input.cget("font")) bold_font.configure(weight="bold") self.main_text_input.tag_configure("keywords", foreground='purple', font=bold_font) self.main_text_input.bind("<space>", self._highlight_keywords) self.main_text_input.insert(1.0, self._ASAO_info()) self.save_button = ttk.Button(self.root, text='Save', command=lambda: self._save()) self.open_button = ttk.Button(self.root, text='Open', command=lambda: self._open()) self.quit_button = ttk.Button(self.root, text='Quit', command=lambda: self._quit()) self.settings_button = ttk.Button(self.root, text='Settings', command=lambda: self._settings()) self.settings_button = ttk.Button(self.root, text='Settings', command=lambda: self._settings()) self.font_frame = ttk.Labelframe(self.root, text='Font Options') self.font_combo = ttk.Combobox(self.font_frame, values=font.families()) self.font_button = ttk.Button(self.font_frame, text='Change Font', command=lambda: self._change_font()) self.font_size = ttk.Spinbox(self.font_frame, from_=1, to=100) self.font_opt = ttk.Combobox(self.font_frame, values=('normal', 'bold', 'italic', 'bold italic'))
def __init__(self, master, **kwargs): super().__init__(**kwargs) self.master = master self.transient(self.master) self.geometry('500x250') self.title('Choose font and size') self.configure(bg=self.master.background) self.font_list = tk.Listbox(self, exportselection=False) self.available_fonts = sorted(families()) for family in self.available_fonts: self.font_list.insert(tk.END, family) current_selection_index = self.available_fonts.index( self.master.font_family) if current_selection_index: self.font_list.select_set(current_selection_index) self.font_list.see(current_selection_index) self.size_input = tk.Spinbox(self, from_=0, to=99, value=self.master.font_size) self.save_button = ttk.Button(self, text="Save", style="editor.TButton", command=self.save) self.save_button.pack(side=tk.BOTTOM, fill=tk.X, expand=1, padx=40) self.font_list.pack(side=tk.LEFT, fill=tk.Y, expand=1) self.size_input.pack(side=tk.BOTTOM, fill=tk.X, expand=1)
def __init__(self, master, fonts): Toplevel.__init__(self, master) self.master = master self.font = fonts self.grab_set() labels = ['Betűtítpus: ', 'Méret: ', 'Stílus: ', ''] for x in range(4): labels[x] = Label(self, text=labels[x]) labels[x].grid(row=x, column=0, sticky=E) self.combos = [0] * 4 self.combo_opts = [ font.families(), [9, 10, 11, 12, 14, 16, 18, 20], ['normal', 'bold'], ['roman', 'italic'] ] self.combo_names = ['family', 'size', 'weight', 'slant'] self.entry_svar = [ StringVar(self), StringVar(self), StringVar(self), StringVar(self) ] for x in range(4): self.combos[x] = ttk.Combobox(self, textvariable=self.entry_svar[x], values=self.combo_opts[x]) self.combos[x].grid(row=x, column=1) self.entry_svar[x].set(self.font.cget(self.combo_names[x])) b_confirm = ttk.Button(self, command=self.end, text="OK") b_confirm.grid(row=4, column=1, padx=10) self.title('Betűtípus') self.geometry( "+%d+%d" % (self.master.winfo_rootx() + 50, self.master.winfo_rooty() + 50)) #self.protocol("WM_DELETE_WINDOW", self.set_destroyed) self.resizable(0, 0) self.transient(self.master)
def __init__(self, master, mainmenu): # the master is the root tk instance! super().__init__(master) self.fontfamilies = set(tkf.families(master)) self.font = mainmenu.font.copy() self.family = self.dfn = self.font['family'] self.size = self.font['size'] self.fontfamilies.add(self.dfn) self.fontfamilies = sorted(self.fontfamilies) # size is width:500 height:400 # place it in the center of the screen x = master.winfo_screenwidth() // 2 - 250 y = master.winfo_screenheight() // 2 - 200 self.geometry('500x400+{}+{}'.format(x, y)) # set to not resizable so that the windows size won't change # if the font family changed (only work when set the size first) self.resizable(0,0) self.left() self.right()
def font_families(): """Returns all the system-specific font families, plus the three guaranteed built-in font families""" return sorted(set(tkfont.families()) | {"Helvetica", "Times", "Courier"})
def __init__(self): """Initialize widgets, methods.""" tkinter.Tk.__init__(self) self.grid() fontoptions = families(self) font = Font(family="Verdana", size=10) menubar = tkinter.Menu(self) fileMenu = tkinter.Menu(menubar, tearoff=0) editMenu = tkinter.Menu(menubar, tearoff=0) fsubmenu = tkinter.Menu(editMenu, tearoff=0) ssubmenu = tkinter.Menu(editMenu, tearoff=0) # adds fonts to the font submenu and associates lambda functions for option in fontoptions: fsubmenu.add_command(label=option, command = lambda: font.configure(family=option)) # adds values to the size submenu and associates lambda functions for value in range(1,31): ssubmenu.add_command(label=str(value), command = lambda: font.configure(size=value)) # adds commands to the menus menubar.add_cascade(label="File",underline=0, menu=fileMenu) menubar.add_cascade(label="Edit",underline=0, menu=editMenu) fileMenu.add_command(label="New", underline=1, command=self.new, accelerator="Ctrl+N") fileMenu.add_command(label="Open", command=self.open, accelerator="Ctrl+O") fileMenu.add_command(label="Save", command=self.save, accelerator="Ctrl+S") fileMenu.add_command(label="Exit", underline=1, command=exit, accelerator="Ctrl+Q") editMenu.add_command(label="Copy", command=self.copy, accelerator="Ctrl+C") editMenu.add_command(label="Cut", command=self.cut, accelerator="Ctrl+X") editMenu.add_command(label="Paste", command=self.paste, accelerator="Ctrl+V") editMenu.add_cascade(label="Font", underline=0, menu=fsubmenu) editMenu.add_cascade(label="Size", underline=0, menu=ssubmenu) editMenu.add_command(label="Color", command=self.color) editMenu.add_command(label="Bold", command=self.bold, accelerator="Ctrl+B") editMenu.add_command(label="Italic", command=self.italic, accelerator="Ctrl+I") editMenu.add_command(label="Underline", command=self.underline, accelerator="Ctrl+U") editMenu.add_command(label="Overstrike", command=self.overstrike, accelerator="Ctrl+T") editMenu.add_command(label="Undo", command=self.undo, accelerator="Ctrl+Z") editMenu.add_command(label="Redo", command=self.redo, accelerator="Ctrl+Y") self.config(menu=menubar) """Accelerator bindings. The cut, copy, and paste functions are not bound to keyboard shortcuts because Windows already binds them, so if Tkinter bound them as well whenever you typed ctrl+v the text would be pasted twice.""" self.bind_all("<Control-n>", self.new) self.bind_all("<Control-o>", self.open) self.bind_all("<Control-s>", self.save) self.bind_all("<Control-q>", self.exit) self.bind_all("<Control-b>", self.bold) self.bind_all("<Control-i>", self.italic) self.bind_all("<Control-u>", self.underline) self.bind_all("<Control-T>", self.overstrike) self.bind_all("<Control-z>", self.undo) self.bind_all("<Control-y>", self.redo) self.text = ScrolledText(self, state='normal', height=30, wrap='word', font = font, pady=2, padx=3, undo=True) self.text.grid(column=0, row=0, sticky='NSEW') # Frame configuration self.grid_columnconfigure(0, weight=1) self.resizable(True, True)
global THE_LED value = line.split(":") mode = int(value[-1]) print("mode="+str(mode)) if mode == 1: #wired THE_LED.set(COLOR_BLUE) else: #Wireless THE_LED.set(COLOR_GREEN) #UI Init root = Tk() root.title("Key binder for Z1 Controler") appHighlightFont = font.Font(family='Helvetica', size=15, weight='bold') font.families() mainframe = ttk.Frame(root, padding="3 3 12 12") mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) #Elements ttk.Label(mainframe, text="Click on a button to bind a key!", font=appHighlightFont).grid(column=2, row=0, columnspan=4, sticky=N) #Joystick ttk.Button(mainframe, text="Left", command=lambda: showMsg("Jleft")).grid(column=0, row=2, sticky=E) ttk.Button(mainframe, text="Up", command=lambda: showMsg("Jup")).grid(column=1, row=1, sticky=N) ttk.Button(mainframe, text="Right", command=lambda: showMsg("Jright")).grid(column=2, row=2, sticky=W) ttk.Button(mainframe, text="Down", command=lambda: showMsg("Jdown")).grid(column=1, row=3, sticky=N)
#adding combobox for font style inside toolview fontvar = StringVar() fontsize = IntVar() fontvar.set('Arial') fontsize.set(25) def fontchange(e): global text_area text_area.configure(font=(fontvar.get(), fontsize.get())) fontbox = ttk.Combobox(toolview, state='readonly', value=font.families(), textvariable=fontvar) #adding font size box sizebox = ttk.Combobox(toolview, state='readonly', value=[i for i in range(1, 100)], textvariable=fontsize) fontbox.bind('<<ComboboxSelected>>', fontchange) sizebox.bind('<<ComboboxSelected>>', fontchange) fontbox.grid(row=0, column=0) sizebox.grid(row=0, column=1) #adding menubar main_menu = Menu(root)
from textobject import TextObject #Import the TextObject class from textobject.py. import tools #Import tools from tools.py. from fmcommands import * #Import the fmcommands module from fcommands.py. import ctypes #Import ctypes to fix text blur. import globals #Global Variables to be used all throughout the place. globals.Init() globals.data = tools.LoadLanguageText() #Load the text from the JSON File. ctypes.windll.shcore.SetProcessDpiAwareness(1) #Fix text blur. #Create main window. globals.mainwindow = Tk() for f in font.families(): print(f) #Create text object. globals.tobject = TextObject(globals.mainwindow) #Remove these to disable dark mode. globals.tobject.BGColor("#000000") globals.tobject.TextColor("#FFFFFF") globals.tobject.CursorColor("#FFFFFF") #Create menu bar. globals.menubar = Menu(globals.mainwindow) #File Menu. globals.filemenu = Menu(globals.menubar, tearoff = False, font = tools.GetFont("menu")) #Create File Menu.
import tkinter.font as tkFont root = tk.Tk() # Create named fonts, reading the current defaults # (thus if users use option database files, this honors their settings). mainFontDescr = tk.Button()["font"] # same as Label, Checkbutton, Menu... entryFontDescr = tk.Entry()["font"] # same as Text mainFont = tkFont.Font(font=mainFontDescr) entryFont = tkFont.Font(font=entryFontDescr) # Set the option database; be sure to set the more general options first. root.option_add("*Font", mainFont) root.option_add("*Entry*Font", entryFont) root.option_add("*Text*Font", entryFont) # This is a quick and dirty demo of live font update tk.Label(root, text="Test Label").pack() fontList = tkFont.families() entryVar = tk.StringVar() entryVar.set(mainFont.cget("family")) def setMainFont(varName, *args): mainFont.configure(family=root.globalgetvar(varName)) entryVar.trace_variable("w", setMainFont) mainMenu = tk.OptionMenu(root, entryVar, *fontList) mainMenu.pack() root.mainloop()
def widgets(self): "Configuration des widgets" # Police d'écriture par défaut self.our_font = font.Font(family='Helvetica', size='32') # Configuration du cadre pour la zone de texte my_frame = tk.Frame(root, width=510, height=275) my_frame.pack(pady=10) my_frame.grid_propagate(False) # Taille limitée my_frame.columnconfigure(0, weight=10) # retour chariot # Configuration de la zone de texte my_text = tk.Text(my_frame, font=self.our_font) my_text.grid(row=0, column=0) # my_text.grid_rowconfigure(0, weight=1) # my_text.grid_columnconfigure(0, weight=1) # Cadre pour les zones de listes bottom_frame = tk.Frame(root) bottom_frame.pack() # Ajout de titres font_label = tk.Label(bottom_frame, text="Police", font='Helvetica 14') font_label.grid(row=0, column=0, padx=10, sticky='W') size_label = tk.Label(bottom_frame, text="Taille", font='Helvetica 14') size_label.grid(row=0, column=1, sticky='W') style_label = tk.Label(bottom_frame, text="Style", font='Helvetica 14') style_label.grid(row=0, column=2, padx=10, sticky='W') # Zone de liste pour la police d'écriture self.my_listbox = tk.Listbox( bottom_frame, selectmode='single', width=40) self.my_listbox.grid(row=1, column=0, padx=10) # Zone de liste pour la taille d'écriture self.font_size_listbox = tk.Listbox( bottom_frame, selectmode='single', width=20) self.font_size_listbox.grid(row=1, column=1) # Zone de liste pour le style d'écriture self.font_style_listbox = tk.Listbox( bottom_frame, selectmode='single', width=20) self.font_style_listbox.grid(row=1, column=2, padx=10) # Insertion dans la zone de liste de la police d'écritures # toutes les polices d'écritures possibles for f in font.families(): self.my_listbox.insert('end', f) # Insertion dans la zone de taille de la police d'écritures # toutes les tailles de police possibles self.font_sizes = [8, 10, 12, 14, 16, 18, 20, 36, 48] for size in self.font_sizes: self.font_size_listbox.insert('end', size) # Insertion dans la zone de style de la police d'écritures # toutes les styles de police possibles self.font_styles = ["Normal", "Gras", "Italique", "Gras et italique", "Souligné", "Barré"] for style in self.font_styles: self.font_style_listbox.insert('end', style) # Action effectuée selon la police d'écriture sélectionnée self.my_listbox.bind( '<ButtonRelease-1>', self.font_chooser) # Action effectuée selon la taille d'écriture sélectionnée self.font_size_listbox.bind( '<ButtonRelease-1>', self.font_size_chooser) # Action effectuée selon le style d'écriture sélectionné self.font_style_listbox.bind( '<ButtonRelease-1>', self.font_style_chooser)
""" Code illustration: 8.09 Fetching tuple of all fonts installed on a system Tkinter GUI Application Development Blueprints """ from tkinter import * from tkinter import font root = Tk() all_fonts = font.families() print(all_fonts)
def __init__(self, window): """Initialize the GUI""" # ttk styling theme per user operating system if gotTtk: themeStyle = ttk.Style() if pl.system() == "Linux" and "clam" in themeStyle.theme_names(): themeStyle.theme_use("clam") elif pl.system() == "Windows" and "winnative" in themeStyle.theme_names(): themeStyle.theme_use("winnative") elif pl.system() == "Windows" and "vista" in themeStyle.theme_names(): themeStyle.theme_use("vista") elif pl.system() == "Windows" and "xpnative" in themeStyle.theme_names(): themeStyle.theme_use("xpnative") elif "aqua" in themeStyle.theme_names(): themeStyle.theme_use("aqua") elif "alt" in themeStyle.theme_names(): themeStyle.theme_use("alt") else: themeStyle.theme_use("default") if inConsole: print("Using ttk style theme:",themeStyle.theme_use()) # Globally set items textSelectColor = "#99CCFF" #bgColor = "#D1D1CE" # No longer used, kept here for reference availFonts = tkfont.families() textFont = "" for x in ("dejavu sans mono","monaco","console","consolas","monospace","sans mono", "liberation mono","courier","mono","helvetica","arial"): try: # Take the first font that at least partly matches x textFont = [y for y in availFonts if x in y.lower()][0] break except: # Fail silently, continue font search pass if inConsole: print("Using text font:",textFont) textFontSize = "10" commentChar = "#" # Could be any -single- 1 in [#$;:/*\\] numChars = 72 # --------------------- CREATE WIDGETS --------------------- # --------------------- Top level window window.title("Comment Block Maker") # Format the window winTop = window.winfo_toplevel() # Size of widgets within frames decides actual dimensions winTop.minsize(width=800, height=480) # Account for menu winTop.maxsize(width=4000, height=3000) window.minsize(width=800, height=480) window.maxsize(width=4000, height=3000) winTop.resizable(True, True) # --------------------- Application top level menu # Menu commands must be defined before menus def copy_block(): """Copies text from the Comment Block text box to the system clipboard""" # Clipboard may be lost once app quits (but comment block is written to Terminal) commentBlock = commentText.get("1.0", "end") winTop.clipboard_clear() winTop.clipboard_append(commentBlock) def paste_plain(): """Pastes text from the system clipboard into the Plain Text box""" hasFocus = winTop.focus_get() try: pasteText = winTop.selection_get(selection = "CLIPBOARD") #inputText.delete("1.0", "end") inputText.insert("end", pasteText) except: pass # Fail silently def load_file(): """Load a text file into the Plain Text box""" filePath = fd.askopenfilename(filetypes=[("All","*"), ("Plain Text","*.txt")]) if filePath: try: lFile = open(filePath, mode='r') lText = lFile.read() lFile.close() inputText.delete("1.0", "end") inputText.insert("1.0", lText) if inConsole: print("Loaded file: "+filePath) except Exception as e: # Negative number for size in pixels not points window.option_add('*Dialog.msg.font', '-weight normal -size -12') msgText = "Error loading file " + filePath + "\n\n" + str(e) msg.showerror("Error", msgText, default=msg.OK) window.option_clear() def help_about(): """About info box""" window.option_add('*Dialog.msg.font', '-weight normal -size -12') msgText = " COMMENT BLOCK MAKER\n\n" msgText += "Copyright 2015 Karl Dolenc, beholdingeye.com. All rights reserved.\n\n" msgText += "Licensed under the GPL License as open source, free software.\n\n" msgText += "You may freely use, copy, modify and distribute this software." msg.showinfo("About", msgText, default=msg.OK) window.option_clear() def help_instructions(): """Instructions for use""" window.option_add('*Dialog.msg.font', '-weight normal -size -12') msgText = "\nConvert a text string to a 72 character wide comment block.\n\n" msgText += "Lines 66 characters long or shorter and starting with 5 hyphens or more\n" msgText += "can be centered as titles; check the 'Center -----Titles' button.\n\n" msgText += "Check the 'Padding Start/End' button to add an empty line at " msgText += "the beginning and end of the comment block.\n\n" msgText += "Reverting the comment block back to plain text may not reproduce " msgText += "the original text. Tabs are converted to spaces, some spaces may be " msgText += "removed, and line breaks changed.\n" msg.showinfo("Usage Instructions", msgText, default=msg.OK) window.option_clear() def quit_from_menu(): """Print Comment box contents in Terminal and exit""" if len(commentText.get("1.0", "end")) > 1: if inConsole: print("Comment block:") print(commentText.get("1.0", "end")) if inConsole: print("Done.") winTop.quit() # --------------------- Menu items mainMenu = tk.Menu(winTop) # File menu fileMenu = tk.Menu(mainMenu, tearoff=0) mainMenu.add_cascade(label="File", menu=fileMenu) if pl.mac_ver()[0] != '': # We're in Mac OS fileMenu.add_command(label="Load Plain Text File...", command=load_file, accelerator="Cmd - O") fileMenu.add_command(label="Quit", command=quit_from_menu, accelerator="Cmd - Q") else: fileMenu.add_command(label="Load Plain Text File...", command=load_file, accelerator="Ctrl - O") fileMenu.add_command(label="Quit", command=quit_from_menu, accelerator="Ctrl - Q") # Edit menu editMenu = tk.Menu(mainMenu, tearoff=0) mainMenu.add_cascade(label="Edit", menu=editMenu) editMenu.add_command(label="Copy Comment Block", command=copy_block) editMenu.add_command(label="Paste Plain Text", command=paste_plain) # Help menu helpMenu = tk.Menu(mainMenu, tearoff=0) mainMenu.add_cascade(label="Help", menu=helpMenu) helpMenu.add_command(label="About", command=help_about) helpMenu.add_command(label="Usage Instructions", command=help_instructions) winTop.config(menu=mainMenu) # --------------------- Window frame of 3 rows # Top window frame, containing three rows if gotTtk: winFrame = ttk.Frame(window) # Needed as top object else: winFrame = tk.Frame(window) winFrame.columnconfigure(0, minsize=800, pad=0, weight=1) # Need weight for stretching winFrame.rowconfigure(0, minsize=5, pad=0, weight=0) # Top and bottom rows are static winFrame.rowconfigure(1, minsize=200, pad=0, weight=10) winFrame.rowconfigure(2, minsize=20, pad=0, weight=0) # Top row frame if gotTtk: topRow = ttk.Frame(winFrame, relief="flat") else: topRow = tk.Frame(winFrame, relief="flat") # Middle row frame, containing three columns if gotTtk: midRow = ttk.Frame(winFrame, relief="flat") else: midRow = tk.Frame(winFrame, relief="flat") midRow.columnconfigure(0, minsize=300, pad=0, weight=1) # Input box to stretch less... midRow.columnconfigure(1, minsize=100, pad=0, weight=0) midRow.columnconfigure(2, minsize=300, pad=0, weight=2) # ...than the comment box midRow.rowconfigure(0, minsize=400, pad=0, weight=1) # Account for other rows # Bottom row frame if gotTtk: bottomRow = ttk.Frame(winFrame, relief="flat") else: bottomRow = tk.Frame(winFrame, relief="flat") # --------------------- Top row contents # None # --------------------- Mid row contents # Left vertical frame, containing two rows if gotTtk: frameLeft = ttk.Frame(midRow, width=200, height=400) else: frameLeft = tk.Frame(midRow, width=200, height=400) frameLeft.columnconfigure(0, minsize=200, pad=0, weight=1) frameLeft.rowconfigure(0, minsize=200, pad=0, weight=10) frameLeft.rowconfigure(1, minsize=5, pad=0, weight=0) # Bottom row is static # The two horizontal frames within if gotTtk: frameLeftTop = ttk.LabelFrame(frameLeft) else: frameLeftTop = tk.LabelFrame(frameLeft) frameLeftTop.config(width=200, height=200, text=" Plain Text Input ") if gotTtk: frameLeftBottom = ttk.Frame(frameLeft) else: frameLeftBottom = tk.Frame(frameLeft) frameLeftBottom.config(width=200, height=5) # --------------------- Plain Text Input box frame inputTextFrame = tk.Frame(frameLeftTop, border=1, relief="flat", highlightthickness=1, highlightcolor="gray") # No need for ttk # Text height / width is in lines and characters, not pixels # No Text widget in ttk inputText=tk.Text(inputTextFrame, height=1, width=1, borderwidth=0, font=(textFont, textFontSize), selectbackground=textSelectColor, selectforeground="black", padx=4, pady=4, relief="flat", undo=True, wrap="word", highlightthickness=0, name="inputText") # Without testing inConsole, script could freeze here if not inConsole: inputText.insert("end", sys.stdin.read()) # Scrollbar for text box if gotTtk: inputScroll=ttk.Scrollbar(inputTextFrame, name="inputScroll") else: inputScroll=tk.Scrollbar(inputTextFrame, name="inputScroll") inputScroll.config(orient="vertical", command=inputText.yview) inputText.configure(yscrollcommand=inputScroll.set) # Middle vertical frame if gotTtk: frameMiddle = ttk.Frame(midRow, width=100, height=400) else: frameMiddle = tk.Frame(midRow, width=100, height=400) # Convert and Revert buttons if gotTtk: btnConvert = ttk.Button(frameMiddle, name="btnConvert", text="Convert ->") btnRevert = ttk.Button(frameMiddle, name="btnRevert", text="<- Revert") else: btnConvert = tk.Button(frameMiddle, name="btnConvert", text="Convert ->") btnRevert = tk.Button(frameMiddle, name="btnRevert", text="<- Revert") # --------------------- Preferences # Alignment options if gotTtk: alignFrame = ttk.LabelFrame(frameMiddle) else: alignFrame = tk.LabelFrame(frameMiddle) alignFrame.config(width=100, height=150, text=" Align Comments ") radioAlignCtrl = tk.IntVar() if gotTtk: radioAlignLeft = ttk.Radiobutton(alignFrame, name="radioAlignLeft") else: radioAlignLeft = tk.Radiobutton(alignFrame, name="radioAlignLeft") radioAlignLeft.config(text="Left", value=0, variable=radioAlignCtrl) if gotTtk: radioAlignCenter = ttk.Radiobutton(alignFrame, name="radioAlignCenter") else: radioAlignCenter = tk.Radiobutton(alignFrame, name="radioAlignCenter") radioAlignCenter.config(text="Center", value=1, variable=radioAlignCtrl) radioAlignLeft.invoke() centerTitlesCtrl = tk.IntVar() if gotTtk: checkCenterTitles = ttk.Checkbutton(alignFrame, name="checkCenterTitles") else: checkCenterTitles = tk.Checkbutton(alignFrame, name="checkCenterTitles") checkCenterTitles.config(text="Center -----Titles", variable=centerTitlesCtrl) # Option to pad with empty line at start and end of block padLinesCtrl = tk.IntVar() if gotTtk: checkPadLines = ttk.Checkbutton(frameMiddle, name="checkPadLines") else: checkPadLines = tk.Checkbutton(frameMiddle, name="checkPadLines") checkPadLines.config(text="Padding Start/End", variable=padLinesCtrl) # Right vertical frame if gotTtk: frameRight= ttk.Frame(midRow, width=400, height=400) else: frameRight= tk.Frame(midRow, width=400, height=400) frameRight.columnconfigure(0, minsize=300, pad=0, weight=1) frameRight.rowconfigure(0, minsize=200, pad=0, weight=10) frameRight.rowconfigure(1, minsize=5, pad=0, weight=0) # Two horizontal frames within if gotTtk: frameRightTop = ttk.LabelFrame(frameRight) else: frameRightTop = tk.LabelFrame(frameRight) frameRightTop.config(width=400, height=200, text=" Comment Block Output ") if gotTtk: frameRightBottom = ttk.Frame(frameRight, width=400, height=5) else: frameRightBottom = tk.Frame(frameRight, width=400, height=5) # --------------------- Comment Box Text box frame commentTextFrame = tk.Frame(frameRightTop, border=1, relief="flat", highlightthickness=1, highlightcolor="gray") commentText=tk.Text(commentTextFrame, height=1, width=1, borderwidth=0, font=(textFont, textFontSize), selectbackground=textSelectColor, selectforeground="black", padx=4, pady=4, relief="flat", undo=True, wrap="none", highlightthickness=0, name="commentText") # Scrollbar for text box if gotTtk: commentScroll=ttk.Scrollbar(commentTextFrame, name="commentScroll") else: commentScroll=tk.Scrollbar(commentTextFrame, name="commentScroll") commentScroll.config(orient="vertical", command=commentText.yview) commentText.configure(yscrollcommand=commentScroll.set) # --------------------- Bottom row contents # Quit button if gotTtk: btnQuit = ttk.Button(bottomRow, name="btnQuit") else: btnQuit = tk.Button(bottomRow, name="btnQuit") btnQuit.config(text="Quit", command=quit_from_menu) # Window resizing corner widget, only in ttk if gotTtk: winGrip = ttk.Sizegrip(window) # --------------------- CALLBACKS & COMMANDS --------------------- # These methods need to be in the scope of __init__ def convert_text(): """Convert plain text input to comment block""" inputString = inputText.get("1.0", "end") if len(inputString) > 999999: # Let's stay sane print("Text too long. Work with chunks shorter than 1,000,000 characters.") return commentBlock = convert_to_comment(inputString, radioAlignCtrl.get(), centerTitlesCtrl.get(), padLinesCtrl.get(), commentChar, numChars) commentText.delete("1.0", "end") commentText.insert("1.0", commentBlock) # Convert button binding btnConvert.config(command=convert_text) def revert_text(): """Revert comment block to plain text""" commentBlock = commentText.get("1.0", "end") revertedString = revert_to_plain(commentBlock, commentChar) inputText.delete("1.0", "end") inputText.insert("1.0", revertedString) # Revert button binding btnRevert.config(command=revert_text) # --------------------- Event handlers def mouse_wheel_scroll(event): """Mousewheel scrolling of Text box scrollbars""" scrollCount = 0 # Linux v. Windows v. Mac if event.num == 5 or event.delta == -120 or event.delta == -1: scrollCount = 2 elif event.num == 4 or event.delta == 120 or event.delta == 1: scrollCount = -2 if str(event.widget).split(".")[-1] == "inputScroll": # Name is last in .path inputText.yview_scroll(scrollCount, "units") if str(event.widget).split(".")[-1] == "commentScroll": commentText.yview_scroll(scrollCount, "units") # Mousewheel binding inputScroll.bind("<MouseWheel>", mouse_wheel_scroll) # Windows/Mac inputScroll.bind("<Button-4>", mouse_wheel_scroll) # Linux (Up) inputScroll.bind("<Button-5>", mouse_wheel_scroll) # Linux (Down) commentScroll.bind("<MouseWheel>", mouse_wheel_scroll) commentScroll.bind("<Button-4>", mouse_wheel_scroll) commentScroll.bind("<Button-5>", mouse_wheel_scroll) def resize_window(event): """Resizing window with winGrip widget""" x1 = window.winfo_pointerx() y1 = window.winfo_pointery() x0 = window.winfo_rootx() y0 = window.winfo_rooty() window.geometry("%sx%s" % (max((x1-x0),800),max((y1-y0),480))) return # Window resizing call if gotTtk: winGrip.bind("<B1-Motion>", resize_window) def quit_app(event): """Quit application""" quit_from_menu() # Obtain text on close of window window.wm_protocol("WM_DELETE_WINDOW", quit_from_menu) # No event passed # Quit accelerator binding if pl.mac_ver()[0] != '': winTop.bind_all("<Command-q>", quit_app) else: winTop.bind_all("<Control-q>", quit_app) def open_app(event): """Run the Load File command""" load_file() # Load File accelerator binding if pl.mac_ver()[0] != '': winTop.bind_all("<Command-o>", open_app) else: winTop.bind_all("<Control-o>", open_app) # --------------------- PLACE WIDGETS --------------------- # Window of 3 rows winFrame.pack(side="top", fil="both", expand=True) topRow.grid(column=0, row=0, sticky="wens") midRow.grid(column=0, row=1, sticky="wens") bottomRow.grid(column=0, row=2, sticky="wens") # --------------------- Top row contents # None # --------------------- Mid row contents # Left column frameLeft.grid(column=0, row=0, sticky="wens") frameLeftTop.grid(column=0, row=0, padx=10, pady=10, sticky="wens") frameLeftBottom.grid(column=0, row=1, sticky="wens") # Text box inputTextFrame.pack(side="top", fill="both", expand=True, padx=20, pady=20) inputText.pack(side="left", fill="both", expand=True) inputScroll.pack(side="right", fill="y", expand=False) # Middle column frameMiddle.grid(column=1, row=0, sticky="wens") # Comment block alignment buttons alignFrame.grid(column=0, row=0, pady=10, ipady=10) radioAlignLeft.grid(column=0, row=0, padx=10, pady=10, sticky="w") radioAlignCenter.grid(column=1, row=0, padx=10, sticky="w") checkCenterTitles.grid(column=0, columnspan=2, row=1, padx=10, sticky="w") checkPadLines.grid(column=0, row=1, padx=10, pady=10) btnConvert.grid(column=0, row=2, pady=30) btnRevert.grid(column=0, row=3) # Right column frameRight.grid(column=2, row=0, sticky="wens") frameRightTop.grid(column=0, row=0, padx=10, pady=10, sticky="wens") frameRightBottom.grid(column=0, row=1, sticky="wens") # Text box commentTextFrame.pack(side="top", fill="both", expand=True, padx=20, pady=20) commentText.pack(side="left", fill="both", expand=True) commentScroll.pack(side="right", fill="y", expand=False) # --------------------- Bottom row contents btnQuit.pack(side="bottom", padx=20, pady=10, ipadx=10) if gotTtk: winGrip.place(relx=1.0, rely=1.0, anchor="se") winGrip.lift()
def __init__(self, parent, *args, **kwargs): Label.__init__(self, parent, *args, **kwargs) self.parent = parent self.pack(side=TOP, fill=X) ################################################################# # Combo Box for font size self.cbFont=ttk.Combobox(self) self.cbFont.pack(side=LEFT, padx=(5, 10)) # Combo Box for font size self.cbFontSize = ttk.Combobox(self) self.cbFontSize.pack(side=LEFT) ################################################################ self.boldIcon = PhotoImage(file='icons/bold.png') btnBold = Button(self, image=self.boldIcon, command=self.parent.changeBold) btnBold.pack(side=LEFT, padx=5) ################################################################ self.italicIcon = PhotoImage(file='icons/italic.png') btnItalic = Button(self, image=self.italicIcon, command=self.parent.changeItalic) btnItalic.pack(side=LEFT, padx=5) ################################################################ self.underlineIcon = PhotoImage(file='icons/under_line.png') btnUnderline = Button(self, image=self.underlineIcon, command=self.parent.changeUnderline) btnUnderline.pack(side=LEFT, padx=5) ################################################################ self.fontcolorIcon = PhotoImage(file='icons/color.png') btnfontColor = Button(self, image=self.fontcolorIcon, command=self.parent.changeFontColor) btnfontColor.pack(side=LEFT, padx=5) ################################################################ self.alignLeftIcon = PhotoImage(file='icons/alignleft.png') btnalignLeft = Button(self, image=self.alignLeftIcon, command=self.parent.alignLeft) btnalignLeft.pack(side=LEFT, padx=5) ################################################################ self.alignCenterIcon = PhotoImage(file='icons/aligncenter.png') btnalignCenter = Button(self, image=self.alignCenterIcon, command=self.parent.alignCenter) btnalignCenter.pack(side=LEFT, padx=5) ################################################################ self.alignRightIcon = PhotoImage(file='icons/alignright.png') btnalignRight = Button(self, image=self.alignRightIcon, command=self.parent.alignRight) btnalignRight.pack(side=LEFT, padx=5) ################################################################ fonts = font.families() fontList = [] fontSizeList = [] for i in range(8,80): fontSizeList.append(i) for i in fonts: fontList.append(i) self.fontVar = StringVar() self.cbFont.config(values=fontList, textvariable=self.fontVar) self.cbFont.current(0) self.cbFontSize.config(values=fontSizeList) self.cbFontSize.current(4) # Create a binding function for font combo box self.cbFont.bind(sequence="<<ComboboxSelected>>", func=self.parent.getFont) # Create a binding function for font size combo box self.cbFontSize.bind(sequence="<<ComboboxSelected>>", func=self.parent.getFontSize)
def __init__(self, duellists, pipe_in, pipe_out, family=None, play_audio=False): super(Ring, self).__init__() self.pipe_in = pipe_in self.pipe_out = pipe_out self.window = tk.Tk() sprites = get_sprites() self.play_audio = play_audio if family in font.families(): fonts = { 'name': font.Font(family=family, size=100), 'sequence': font.Font(family=family, size=50), 'to_parry': font.Font(family=family, size=50) } else: fonts = { 'name': font.Font(size=100), 'sequence': font.Font(size=50), 'to_parry': font.Font(size=50) } basic_config = { 'bg': '#ebcd89', 'fg': '#64330c', 'fonts': fonts, 'max_timeout': GUI_MAX_TIMEOUT } configs = {device_id: self.make_config(basic_config, duellist) for device_id, duellist in enumerate(duellists)} configs[0]['adversery_color'] = configs[1]['self_color'] configs[1]['adversery_color'] = configs[0]['self_color'] if play_audio: from audio.player import Player self.player = Player() self.speach = Thread(target=self.speach_thread) self.speach.start() else: self.player = None self.duellists = {device_id: DuellistFrame(self.window, config, sprites, device_id, self.player, self.pipe_out) for device_id, config in configs.items()} self.duellists[0].pack(side='left', fill='y', expand=True) self.duellists[1].pack(side='right', fill='y', expand=True) self.window.configure(bg=basic_config['bg']) self.window.title('Дуэльный клуб') self.window.bind("<Key>", self.on_key) self.window.protocol("WM_DELETE_WINDOW", self.on_closing) self.in_loop = True self.refresh()
def get_families(): # For some reason, some families start with a '@' on Windows. I'm # not sure why, but let's ignore them for now. return (family for family in font.families() if not family.startswith('@'))
def __init__(self, menubar=None, cnf={}, **kw): import tkinter.font as TkFont kw.pop('tearoff',None) self.root = menubar.root super().__init__(menubar, cnf, tearoff=0, **kw) def change_wsize(func=None): def wrapper(*args): temp = None def before(): # print() # print('before',self.root.mainWindows.geometry()) oldsize = self.root.mainWindows.show_size # print('should', oldsize) xy = tuple(oldsize[2:4]) # print('xy',xy) oldsize = '%dx%d+0+0'%oldsize[4:] self.root.mainWindows.geometry(oldsize) # self.root.mainWindows.withdraw() nonlocal temp temp = xy def do(): before() result = func(*args) if func else None self.after(1000, after) return result def after(): nonlocal temp xy = temp newsize = self.root.mainWindows.show_size # print('new',newsize) newsize = '%dx%d+%d+%d'%(newsize[:2] + xy) self.root.mainWindows.geometry(newsize) # print('new',newsize) # self.root.mainWindows.deiconify() return do() return wrapper def command(Var, index): @change_wsize def func(): ft = self.root.editFont if Var: size = (sizeList[index]) ft.config(size = size) self.root.configs['font']['size'] = str(size) else: family = (fontList[index]) ft.config(family = family) self.root.configs['font']['family'] = family return func @change_wsize def reset(): self.root.editFont.config(**self.root.configs['defaultfont']) def add_value(parent, Var, *List): for index, value in enumerate(List): ft = TkFont.Font(family = 'Fixedsys', size = 10, weight = TkFont.NORMAL) if Var: ft.config(size = value) else: ft.config(family = value) parent.add_command(label=str(value),font=ft, command=command(Var, index)) return parent selectfont = tkinter.Menu(self,tearoff=0) selectsize = tkinter.Menu(self,tearoff=0) fontList = TkFont.families() sizeList = tuple(range(8,51,1)) add_value(selectfont, 0, *fontList) add_value(selectsize, 1, *sizeList) self.add_cascade(label='字体设置', menu=selectfont) self.add_cascade(label='字号设置', menu=selectsize) self.add_command(label='字体重置', command=reset) def popup(event):self.post(event.x_root, event.y_root) self.bind("<Button-3>", popup) menubar.add_cascade(label='字体', menu=self)
##$t.menu.m add command -label "Just" -command [list $w.txt insert end Just\n] ##$t.menu.m add command -label "An" -command [list $w.txt insert end An\n] ##$t.menu.m add command -label "Example" \ ## -command [list $w.txt insert end Example\n] ##bind $t.combo <<ComboboxSelected>> [list changeFont $w.txt $t.combo] ##proc changeFont {txt combo} { ## $txt configure -font [list [$combo get] 10] ##} button = ttk.Button(t, text='Button', style='Toolbutton', command=lambda: txt.insert(END, 'Button Pressed\n')) checkvar = StringVar() check = ttk.Checkbutton(t, text='Check', variable=checkvar, style='Toolbutton', command=lambda: txt.insert(END, "check is "+checkvar.get()+"\n")) menu = ttk.Menubutton(t, text='Menu') from tkinter.font import families combo = ttk.Combobox(t, value=sorted(families()), state='readonly') menu['menu'] = m = Menu(menu) m.add_command(label='Just', command=lambda: txt.insert(END, 'Just\n')) m.add_command(label='An', command=lambda: txt.insert(END, 'An\n')) m.add_command(label='Example', command=lambda: txt.insert(END, 'Example\n')) def changeFont(txt, combo): fname = combo.get() if ' ' in fname: fname = '{' + fname + '}' txt.configure(font=fname+' 10') combo.bind('<<ComboboxSelected>>', lambda e: changeFont(txt, combo)) #### Some content for the rest of the toplevel ##text $w.txt -width 40 -height 10 ##interp alias {} doInsert {} $w.txt insert end ;# Make bindings easy to write txt = Text(w, width=40, height=10)
def __init__(self): self.conn = connect('project_trpo') # подлкючение к БД x = 500 // 2 - 30 height = 70 interval = 60 self.REGISTRATION = Tk() self.REGISTRATION['bg'] = "#444444" self.REGISTRATION.resizable(False, False) self.REGISTRATION.geometry("600x500") self.REGISTRATION.iconbitmap('icon.ico') self.conn.row_factory = self.dict_factory self.label = Label(self.REGISTRATION, text="", fg="#FF002F", bg="#444444", font=font.Font(slant=font.ROMAN, size=10)) self.label.place(x=x - 130, y=height + interval * 2 + 22) self.cursor = self.conn.cursor() self.cursor.execute("SELECT USERNAME FROM users") self.logins = {i["USERNAME"] for i in self.cursor.fetchall()} Label(self.REGISTRATION, text="Логин", fg="#FFFFFF", bg="#444444").place(x=x, y=height + interval * 2) self.login = StringVar() self.ButLog = Entry(self.REGISTRATION, textvariable=self.login, bg="#222222", fg="#FFFFFF", selectbackground="#444444", selectforeground="#19C710", width=13, font=("@Microsoft YaHei UI Light", 16)) self.ButLog.place(x=x, y=height + interval * 2 + 22) self.ButLog.focus_set() self.ButLog.bind( "<Any-KeyRelease>", lambda event: (self.check_login(), self.check_texts())) Label(self.REGISTRATION, text="Пароль", fg="#FFFFFF", bg="#444444").place(x=x, y=height + interval * 3) self.password = StringVar() self.pas = Entry(self.REGISTRATION, textvariable=self.password, show='*', bg="#222222", fg="#FFFFFF", selectbackground="#444444", selectforeground="#19C710", width=13, font=("@Microsoft YaHei UI Light", 16)) self.pas.place(x=x, y=height + interval * 3 + 22) self.pas.bind( "<Any-KeyRelease>", lambda event: (self.check_password(), self.check_texts())) Label(self.REGISTRATION, text="Повторите пароль", fg="#FFFFFF", bg="#444444").place(x=x, y=height + interval * 4) self.second_password = StringVar() self.sec_pas = Entry(self.REGISTRATION, textvariable=self.second_password, show='*', bg="#222222", fg="#FFFFFF", selectbackground="#444444", selectforeground="#19C710", width=13, font=("@Microsoft YaHei UI Light", 16)) self.sec_pas.place(x=x, y=height + interval * 4 + 22) self.sec_pas.bind( "<Any-KeyRelease>", lambda event: (self.check_second_password(), self.check_texts())) Label(self.REGISTRATION, text="Ваше имя", fg="#FFFFFF", bg="#444444").place(x=x, y=height + interval * 0) self.name = StringVar() self.name_Entry = Entry(self.REGISTRATION, textvariable=self.name, bg="#222222", fg="#FFFFFF", selectbackground="#444444", selectforeground="#19C710", width=13, font=("@Microsoft YaHei UI Light", 16)) self.name_Entry.place(x=x, y=height + interval * 0 + 22) self.name_Entry.bind( "<Any-KeyRelease>", lambda event: (self.check_name(), self.check_texts())) Label(self.REGISTRATION, text="Группа", fg="#FFFFFF", bg="#444444").place(x=x, y=height + interval * 1) self.gruop = StringVar() self.gruop_Entry = Entry(self.REGISTRATION, textvariable=self.gruop, bg="#222222", fg="#FFFFFF", selectbackground="#444444", selectforeground="#19C710", width=13, font=("Bahnschrift Light SemiCondensed", 18)) self.gruop_Entry.place(x=x, y=height + interval * 1 + 22) self.gruop_Entry.bind( "<Any-KeyRelease>", lambda event: (self.check_group(), self.check_texts())) fon = list(font.families()) f = font.Font(family=fon[88], size=14) self.b = Button(self.REGISTRATION, text="Регистрация", width=13, height=1, bg='#222222', fg='#EEEEEE', bd=0, activebackground='#333333', activeforeground='#EEEEEE', highlightcolor="black", relief=SUNKEN, font=f, command=self.press) self.b.place(x=220, y=380) self.b['state'] = 'disabled' self.REGISTRATION.bind("<Return>", lambda _: self.press()) self.REGISTRATION.grid() self.REGISTRATION.mainloop()
def __init__(self, parent): self.parent = parent self.selected_family = parent.config[4] self.selected_size = parent.config[5] self.selected_weight = parent.config[6] families = list(OrderedDict.fromkeys(font.families())) families.sort() sizes_low = [x for x in range(7, 19)] sizes_high = [x for x in range(20, 74, 2)] sizes = sizes_low + sizes_high weights = ('normal', 'bold') self.style = Style() self.style.theme_use('clam') self.families = StringVar() self.sizes = StringVar() self.weight = StringVar() self.families.set(tuple(families)) self.sizes.set(tuple(sizes)) self.weight.set(weights) self.font = font.Font(size=9, weight='bold') self.root = Toplevel() self.root.title('pyEdit - Font Selector') self.root.resizable(False, False) self.root.bind('<Expose>', lambda e: Utils.on_expose(self)) self.root.wm_protocol('WM_DELETE_WINDOW', lambda: Utils.on_close(self)) # Family self.lf_family = LabelFrame(self.root, text='Family:', font=self.font, relief='flat') self.lf_family.grid(column=0, row=0, sticky='nsew', padx=5, pady=5) self.frame_family = Frame(self.lf_family) self.frame_family.grid(column=0, row=0, sticky='nsew', padx=5, pady=5) self.listbox_family = Listbox(self.frame_family, bd=0, listvariable=self.families) self.listbox_family.grid(column=0, row=0, sticky='nsew') self.listbox_family.bind('<ButtonRelease-1>', lambda e: self.listbox_event_handler(event=e, listbox='family')) self.scrollbar_family = Scrollbar(self.frame_family, orient='vertical', bd=0, command=self.listbox_family.yview) self.scrollbar_family.grid(column=1, row=0, sticky='ns') self.listbox_family.config(yscrollcommand=self.scrollbar_family.set) # Size self.lf_size = LabelFrame(self.root, text='Size:', font=self.font, relief='flat') self.lf_size.grid(column=1, row=0, sticky='nsew', padx=5, pady=5) self.frame_size = Frame(self.lf_size) self.frame_size.grid(column=0, row=0, sticky='nsew', padx=5, pady=5) self.listbox_size = Listbox(self.frame_size, bd=0, listvariable=self.sizes, width=3) self.listbox_size.grid(column=0, row=0, sticky='nsew') self.listbox_size.bind('<ButtonRelease-1>', lambda e: self.listbox_event_handler(event=e, listbox='size')) self.scrollbar_size = Scrollbar(self.frame_size, orient='vertical', bd=0, command=self.listbox_size.yview) self.scrollbar_size.grid(column=1, row=0, sticky='ns') self.listbox_size.config(yscrollcommand=self.scrollbar_size.set) # Weight self.lf_weight = LabelFrame(self.root, text='Weight:', font=self.font, relief='flat') self.lf_weight.grid(column=0, row=1, sticky='nsew', padx=5, pady=5, columnspan=2) self.lf_weight.columnconfigure(0, weight=1) self.frame_weight = Frame(self.lf_weight) self.frame_weight.grid(column=0, row=0, sticky='nsew', padx=5, pady=5) self.frame_weight.columnconfigure(0, weight=1) self.listbox_weight = Listbox(self.frame_weight, bd=0, listvariable=self.weight, height=2) self.listbox_weight.grid(column=0, row=0, sticky='nsew') self.listbox_weight.bind('<ButtonRelease-1>', lambda e: self.listbox_event_handler(event=e, listbox='weight')) # Slant # self.lf_slant = LabelFrame(self.root, text='Slant:', font=self.font, relief='flat') # self.lf_slant.grid(column=0, row=2, sticky='nsew', padx=5, pady=5, columnspan=2) # self.lf_slant.columnconfigure(0, weight=1) # # self.frame_slant = Frame(self.lf_slant) # self.frame_slant.grid(column=0, row=0, sticky='nsew', padx=5, pady=5) # self.frame_slant.columnconfigure(0, weight=1) # # self.listbox_slant = Listbox(self.frame_slant, listvariable=self.weight, height=2) # self.listbox_slant.grid(column=0, row=0, sticky='nsew') self.frame_btn = Frame(self.root) self.frame_btn.grid(column=0, row=2, sticky='nsew', padx=5, pady=5, columnspan=2) self.frame_btn.columnconfigure(0, weight=1) self.btn_close = Button(self.frame_btn, text='Close', command=lambda: Utils.on_close(self)) self.btn_close.grid(column=0, row=0, sticky='nse', padx=5, pady=5)
from tkinter import * from tkinter import font root = Tk() root.title('Font Families') fonts = list(font.families()) fonts.sort() def populate(frame): '''Put in the fonts''' listnumber = 1 for item in fonts: label = "listlabel" + str(listnumber) label = Label(frame, text=item, font=(item, 16)).pack() listnumber += 1 def onFrameConfigure(canvas): '''Reset the scroll region to encompass the inner frame''' canvas.configure(scrollregion=canvas.bbox("all")) canvas = Canvas(root, borderwidth=0, background="#ffffff") frame = Frame(canvas, background="#ffffff") vsb = Scrollbar(root, orient="vertical", command=canvas.yview) canvas.configure(yscrollcommand=vsb.set) vsb.pack(side="right", fill="y") canvas.pack(side="left", fill="both", expand=True) canvas.create_window((4, 4), window=frame, anchor="nw")
def init_widget (self, **kw): r""" widget main inits; """ # super class inits super().init_widget( # looks for ^/xml/widget/dlg_scenario_elements_editor.xml xml="dlg_scenario_elements_editor", ) # inits self.async = ASYNC.get_async_manager() self.w_text = kw.get("w_text") self.settings = [ # global settings { "element": copy.deepcopy(self.w_text.get_options_element()), "current_selected": 0, }, # project settings { "element": copy.deepcopy(self.w_text.ELEMENT), "current_selected": 0, }, ] self.current_settings = self.settings[0] self.element_names = self.get_element_names( self.current_settings["element"] ) _names = sorted(self.element_names) _readonly = ["readonly"] self.w = self.container # NOTEBOOK section self.NOTEBOOK = self.w.notebook_see_prefs # ELEMENT CHAINING section self.w.combo_current_element.configure( values=_names, state=_readonly ) self.w.combo_current_element.current(0) # update element names for choice selection _names.insert(0, "") # set choice names to all switch/create combos self.CHAINING_NAMES = self.get_chaining_names() self.CHAINING_COMBOS = self.get_chaining_combos() self.CHAININGS = tuple( zip(self.CHAINING_COMBOS, self.CHAINING_NAMES) ) for _w in self.CHAINING_COMBOS: _w.configure(values=_names, state=_readonly) _w.current(0) # end for # FONT section self.w.combo_font_family.configure( values=['courier', 'helvetica', 'times', 'tkdefaultfont'] + sorted(font.families()) ) self.FONT_COMBOS = ( self.w.combo_font_family, self.w.combo_font_size, self.w.combo_font_style ) # MARGIN section _filter = self.register(self.key_filter_digits) self.w.entry_lmargin.configure( validate="key", validatecommand=(_filter, "%S") ) self.w.entry_rmargin.configure( validate="key", validatecommand=(_filter, "%S") ) self.MARGIN_COMBOS = ( self.w.combo_lmargin_units, self.w.combo_rmargin_units ) # init all combos at once for _w in self.FONT_COMBOS + self.MARGIN_COMBOS: _w.state(_readonly) _w.current(0) # end if # PREVIEW section self.w.text_preview.configure( # use only the following attrs from w_text font=self.w_text.cget("font"), background=self.w_text.cget("background"), foreground=self.w_text.cget("foreground"), width=1, height=10, wrap="word", ) # event bindings self.bind_events(**kw) # reset tab along with user option self.NOTEBOOK.select( self.options.get( self.get_rc_section(), "startup_tab_index", fallback=1 ) )
theme_choice.set(color_dict['White Theme']) #################### THEME menu icons options END ###################### # -----------------&&&&&&&&&&&&&&&&&&& MAIN MENU ENDs &&&&&&&&&&&&&&&&&-----------------------# ###################################### TOOL BAR START ######################################### ###################################### TOOL BAR START ######################################### ###################################### TOOL BAR START ######################################### tool_bar = tk.Label(root, border=2, relief=tk.GROOVE, bg="black") tool_bar.pack(side=tk.TOP,fill=tk.X) font_tuple = font.families() # font box font_family = tk.StringVar() font_name_label = tk.Label(tool_bar, text="Font Falimy :", bg="black", fg='white') font_name_label.grid(row=0, column=0, padx=5, pady=(2,0)) fontbox = ttk.Combobox(tool_bar, width=25, textvariable=font_family, state="readonly") fontbox['values'] = font_tuple # font_tuple.index('Arial') ka matlb ye iska index number return karega as integer fontbox.current(font_tuple.index('Arial')) fontbox.grid(row=0, column=1, padx=5, pady=(2,0)) ## size box font_size_label = tk.Label(tool_bar, text="Font Size :", bg="black", fg='white') font_size_label.grid(row=0, column=2, padx=5, pady=(2,0)) size_var = tk.IntVar()
def FindFont(self, families, size, weight=tkfont.NORMAL, slant=tkfont.ROMAN, underlined=False): fontfamilies = tkfont.families() for family in families: if family in fontfamilies: return tkfont.Font(family=family, size=size, weight=weight, slant=slant, underline=underlined) return None
def import_(self): font = Tk() self.parent = font self.parent.geometry('410x350') self.parent.title('Psarris\' Fonts') self.parent.iconbitmap(r'') self.parent.resizable(False, False) # variables self.sizee = 10 self.stylee = 'normal' self.fontt = 'Arial' # font labels font_main = ttk.Label(self.parent, text='Fonts:') font_main.place(x=21, y=25) font_style = ttk.Label(self.parent, text='Style:') font_style.place(x=176, y=25) font_size = ttk.Label(self.parent, text='Size:') font_size.place(x=334, y=25) # listboxes (3) # .. listbox1 self.list_main = Listbox(self.parent, height=6, exportselection=False, relief=SOLID) self.list_scroll = ttk.Scrollbar(self.parent, orient=VERTICAL, command=self.list_main.yview) self.list_main.config(yscrollcommand=self.list_scroll.set) fonts = list(font_.families()) for f in sorted(fonts): self.list_main.insert(END, f) self.list_scroll.place(x=159, y=46, anchor='n', height=116) self.list_main.yview_moveto('0.1') self.list_main.place(x=20, y=44, height=120, width=150) # .. listbox2 self.list_style = Listbox(self.parent, height=6, width=15, exportselection=False, relief=SOLID) self.list_scroll1 = ttk.Scrollbar(self.parent, orient=VERTICAL, command=self.list_style.yview) self.list_style.config(yscrollcommand=self.list_scroll1.set) self.list_style.insert(1, 'normal') self.list_style.insert(2, 'bold') self.list_style.insert(4, 'italic') self.list_style.insert(5, 'bold italic') self.list_scroll1.place(x=314, y=46, anchor='n', height=116) self.list_style.place(x=175, y=44, width=150, height=120) # .. listbox3 self.list_size = Listbox(self.parent, height=6, width=9, relief=SOLID, exportselection=False) self.list_scroll2 = ttk.Scrollbar(self.parent, orient=VERTICAL, command=self.list_size.yview) self.list_size.config(yscrollcommand=self.list_scroll2.set) # 8, 11, 12- 28, 36, 48, 72 self.list_size.insert(1, '8') self.list_size.insert(1, '10') self.list_size.insert(2, '11') for i in range(12, 29): if i % 2 == 0: p = str(i) q = p self.list_size.insert(END, q) self.list_size.insert(END, '36') self.list_size.insert(END, '48') self.list_size.insert(END, '72') self.list_scroll2.place(x=375, y=46, anchor='n', height=116) self.list_size.yview_moveto('0.1') self.list_size.place(x=333, y=44, width=53, height=120) """ add font to each inserted item """ # sample label frames = ttk.Frame(self.parent, width=260, height=80, border=5, relief=SOLID) frames.place(x=255, y=190, anchor='n') frame = ttk.Frame(frames, width=250, height=66, border=5) frame.place(y=35, relx=0.5, rely=0.5, anchor='s') sample_label = ttk.Label(self.parent, text='Sample!') sample_label.place(x=170, y=191, anchor='center', height=20) self.sample_label1 = ttk.Label(frame, text='AaBbCc', font=(self.fontt, self.sizee, self.stylee)) self.sample_label1.place(relx=0.5, rely=0.5, anchor='center') # ok n cancel button (2) ok_button = ttk.Button(self.parent, text='ok', command=self.ok_) ok_button.place(x=220, y=300) cancel_button = ttk.Button(self.parent, text='cancel', command=self.cancel_) cancel_button.place(x=300, y=300) # bindings self.list_main.bind('<<ListboxSelect>>', lambda e: self.change_font()) self.list_style.bind('<<ListboxSelect>>', lambda e: self.change_style()) self.list_size.bind('<<ListboxSelect>>', lambda e: self.change_size()) self.parent.bind('<Return>', lambda a: self.ok_()) # function try: self.list_main.select_set(int(self.x_)) self.list_size.select_set(self.z) self.list_style.select_set(self.y) print('trying') except AttributeError: print('e can work') self.list_main.select_set(33) self.list_size.select_set(0) self.list_size.select_set(1) self.parent.protocol("WM_DELETE_WINDOW", self.cancel_) self.parent.mainloop()
def fontList(): return list(font.families())
root.geometry("200x150") label = Label(root, text="Hello World") label.pack(padx=5, pady=5) root.mainloop() # If you want a list of font families, # you can use the following code. # It will return a list of different font types. import tkinter from tkinter import * from tkinter import font root = Tk() print(font.families()) # Finally, you can change both simultaneously # by writing both at the same time. import tkinter from tkinter import * root = Tk() root.option_add('*Font', 'Times 19') root.geometry("200x150") label = Label(root, text="Hello World") label.pack(padx=5, pady=5) root.mainloop()
def cargar_fonts(self): """Carga los formatos de letras.""" fonts = list(tkFont.families(self.master)) fonts.sort() for font in fonts: self.FUENTES.append(font)
def main(): root = Tk() print(families(root)) Searcher(root) root.mainloop()
def test_families(self): families = font.families(self.root) self.assertIn(self.font.actual('family'), families)
def __init__(self): self.hovedvindu = tkinter.Tk() self.tekstomraadet = tkinter.Text(self.hovedvindu, height=10, width=30) self.tekstomraadet.grid(column=0, row=0) self.scrollbar = tkinter.Scrollbar(self.hovedvindu, orient=tkinter.VERTICAL, command=self.tekstomraadet.yview) self.scrollbar.grid(column=1, row=0, sticky=(tkinter.N, tkinter.S)) self.tekstomraadet.config(yscrollcommand=self.scrollbar.set) self.hovedvindu.title("Enkel teksteditor") self.hovedmeny = tkinter.Menu(self.hovedvindu) self.hovedvindu.config(menu=self.hovedmeny) self.hovedvindu.option_add("*tearOff", False) self.filmeny = tkinter.Menu(self.hovedvindu) self.hovedmeny.add_cascade(menu=self.filmeny, label="Fil") self.redigermeny = tkinter.Menu(self.hovedvindu) self.hovedmeny.add_cascade(menu=self.redigermeny, label="Rediger") self.filmeny.add_command(label="Åpne", command=self.aapne_valg) self.filmeny.add_command(label="Lagre", command=self.lagre_valg) self.filmeny.add_command(label="Lukk") self.redigermeny.add_command(label="Klipp ut") self.redigermeny.add_command(label="Kopier") self.redigermeny.add_command(label="Lim inn") self.knappramme = tkinter.Frame(self.hovedvindu) self.knappramme.grid(column=2, row=0) self.bold_var = tkinter.BooleanVar() self.bold_checkbutton = tkinter.Checkbutton(self.knappramme, text="Bold", variable=self.bold_var, command=self.endre_font) self.bold_checkbutton.pack() self.italic_var = tkinter.BooleanVar() self.italic_checkbutton = tkinter.Checkbutton(self.knappramme, text="Italic", variable=self.italic_var, command=self.endre_font) self.italic_checkbutton.pack() self.font_var = tkinter.IntVar(value=TIMES) self.times = tkinter.Radiobutton(self.knappramme, text="Times new roman", variable=self.font_var, value=TIMES, command=self.endre_font) self.times.pack() self.arial = tkinter.Radiobutton(self.knappramme, text="Arial", variable=self.font_var, value=ARIAL, command=self.endre_font) self.arial.pack() self.courier = tkinter.Radiobutton(self.knappramme, text="Courier New", variable=self.font_var, value=COURIER, command=self.endre_font) self.courier.pack() self.fontlistbox = tkinter.Listbox(self.hovedvindu, selectmode=tkinter.SINGLE) self.fontene = font.families() for fonten in self.fontene: self.fontlistbox.insert(tkinter.END, fonten) self.fontlistbox.grid(column=3, row=0, sticky=(tkinter.N, tkinter.S)) self.fontscroller = tkinter.Scrollbar(self.hovedvindu, orient=tkinter.VERTICAL, command=self.fontlistbox.yview) self.fontlistbox.config(yscrollcommand=self.fontscroller.set) self.fontscroller.grid(column=4, row=0, sticky=(tkinter.N, tkinter.S)) self.fontlistbox.bind("<Double-Button-1>", self.endre_font_listbox) self.fontlistbox.bind("<Key-Return>", self.endre_font_listbox) tkinter.mainloop()
def get_font(family='EB Garamond', size=14): if family not in families(): family = 'Times' return Font(family=family, size=size)