Как загрузить шрифт в python
Перейти к содержимому

Как загрузить шрифт в python

  • автор:

Стилизация

Ряд виджетов, например, Label или Text, поддерживают установку шрифта через параметр font . Каждая платформа может определять свои специфические шрифты. Но также библиотека Tk по умолчанию включает ряд именнованных шрифтов, которые могут использоваться на различных компонентах графического интерфейса и которые доступны на всех платформах:

TkDefaultFont : шрифт по умолчанию, который применяется, если для виджета явным образом не определен шрифт

TkTextFont : шрифт по умолчанию, который применяется для виджетов Entry, Listbox и ряда других

TkFixedFont : шрифт с фиксированной шириной

TkMenuFont : шрифт для пунктов меню

TkHeadingFont : шрифт для заголовков в Listbox и в таблицах

TkCaptionFont : шрифт для строки статуса в окнах

TkSmallCaptionFont : шрифт малого размера для диалоговых окон

TkIconFont : шрифт для подписей к иконкам

TkTooltipFont : шрифт для высплывающих окон

В принципе мы можем использовать эти шрифты не только в любых виджетах:

Tk также предоставляет дополнительный набор именнованных шрифтов, которые определены только на определенных платформах. Для их получения можно использовать функцию names() из пакета tkinter.font :

Например, на Windows мы получим следующий набор:

В данном случае выводятся и платформа-независимые, и платформо-специфичные шрифты, например, «system».

Определение шрифта

За определение шрифта в Tkinter отвечает класс Font из модуля tkinter.font . Он принимет следующие параметры:

name : имя шрифта

family : семейство шрифтов

size : высота шрифта (в точках при положительном значении или в пикселях при негативном значении)

weight : вес шрифта. Принимает значения normal (обычный) или bold (жирный)

slant : наклон. Принимает значения roman (обычный) или italic (наклонный)

underline : подчеркивание. Принимает значения True (с подчеркиванием) или False (без подчеркивания)

overstrike : зачеркивание. Принимает значения True (с зачеркиванием) или False (без зачеркивания)

Для получения всех доступных семейств шрифтов на текущей платформе можно использовать функцию families() из модуля tkinter.font

Пример применения шрифтов:

Шрифты в Tkinter и Python

Также можно использовать определение шрифта в виде строки:

Например, в определении «Arial 11 normal roman» , применяется семейство шрифта Arial, высота 11 единиц, нежирный шрифт без наклона.

How to Use Custom Fonts with Matplotlib — In 5 Minutes or Less

Make your visualizations extra catchy with custom fonts (TTF’s included)

Matplotlib visualizations can be an eyesore by default. Lucikly for you, a lot can be tweaked with a couple of lines of code. Today we’ll take a look at changing fonts and explain why it is generally a good idea.

The article is structured as follows:

  • Custom fonts — Why?
  • Using built-in fonts
  • Using custom fonts from a TTF file
  • Conclusion

Custom fonts — Why?

Why not? The default ones won’t get you far. If your company has a distinct branding, why not use it whenever possible?

Let’s take a look at how default stylings look like. There’s no data visualization without data, so let’s declare a simple dataset first. It contains dummy quarterly sales for an imaginary company:

Here’s how the dataset looks like:

Image 1 — Dummy visualization dataset (image by author)

Image 1 — Dummy visualization dataset (image by author)

Let’s visualize this data with both line and scatter plots. We’ll keep most of the default stylings and just remove the top and right spines:

Here’s the visualization:

Image 2 — Visualization with default fonts (image by author)

Image 2 — Visualization with default fonts (image by author)

As you can see, the fonts look decent, but I don’t know a single brand that uses DejaVu Sans as their font of choice. Let’s see how to change it next.

Using built-in fonts

Matplotlib makes it easy to use fonts installed on your machine. You can use the following code snippet to list the first ten available fonts:

Here are the results:

Image 3 — Preinstalled fonts (image by author)

Image 3 — Preinstalled fonts (image by author)

Remove the [:10] if you want the entire list. You can specify the value for the font parameter to use a font of interest in either title or the axis labels.

The following code snippet shows you how to use Courier New font in the title:

Here’s how the visualization looks like:

Image 4 — Visualization with a preinstalled system font (image by author)

Image 4 — Visualization with a preinstalled system font (image by author)

But did you know there’s no need to install the font before using it? All you need is a TTF file. Let’s explore how that works next.

Using custom fonts from a TTF file

To follow along, please download the Merriweather font from here (or any other). Unzip the file and copy the path to the folder.

From here, we can use the font_manager from Matplotlib to add fonts from a file. You’ll want to add the fonts one by one inside the loop.

Once added, we’ll set the entire Matplotlib font family to Merriweather, so we don’t have to specify the font everywhere manually.

Once that is done, you can make the visualization as you usually would:

The results are shown in the following figure:

Image 5 — Visualization with a custom TTF font (image by author)

Image 5 — Visualization with a custom TTF font (image by author)

And that’s how easy it is to add custom fonts to Matplotlib! Let’s wrap things up next.

Conclusion

Today’s article was short but to the point. You’ve learned how to incorporate your branding into data visualizations, an essential skill if you want to send a consistent message across all mediums.

Stay tuned to the blog if you’ve liked this piece — a bunch more similar articles are coming soon.

Как установить шрифт текстового виджета Tkinter

Как установить шрифт текстового виджета Tkinter

Метод configure виджета Tkinter Text задаёт свойства Text , подобно шрифту текста. Шрифт font может быть как tuple типом, так и объектом Tkinter Font .

Установите Шрифт для Text виджета

Он устанавливает шрифт Courier , курсив с размером 16 .

Установите Шрифт для Tkinter Text Виджет с tkFont

Также мы могли бы установить шрифт с помощью объекта font модуля tkFont .

  1. family — семейство шрифтов, как Arial , Courier
  2. size — размер шрифта (в пунктах)
  3. weight — толщина, normal или bold
  4. slant — наклон шрифта: roman или italic
  5. underline — подчёркивание шрифта, False или True
  6. overstrike — забастовка шрифта, False или True

Преимущество использования объекта Font вместо шрифта tuple заключается в том, что один и тот же объект Font может быть присвоен различным виджетам и программно обновлен методом Font.configure . Все виджеты, имеющие один и тот же объект Font , будут обновлены в новом стиле font .

Он обновляет вес fontExample , чтобы быть normal .

Семейства шрифтов Tkinter

Для вашего удобства мы перечислили все доступные семейства шрифтов в Tkinter (Tkinter 3, Windows OS). Вы также можете перечислить семейства шрифтов в вашей рабочей среде со следующими кодами,

Add custom fonts to Matplotlib

This is step by step guide to install and use a new font in Matplotlib. I have tested this procedure on both Linux and OS X machines. Suppose you are running a Jupyter notebook and you want to change the font of a plot. Here is what you need to do!

  1. First, we need to install our custom font. Keep in mind that Matplotlib expects a font in True Type format (.ttf). For example, if we want to add the Helvetica font, we need to check if we have the font in .ttf format installed on our system otherwise we need to download it and install it.
  2. Next, we need to update the font cache from the command line with the following command:

That’s it! Now we need to instruct Matplotlib to use our custom font. Suppose that we want to plot a bar chart and change the labels and ticks font. In this case, just for visual purposes, we will use the Comic Sans font.

Now, let’s try to plot it and see the actual result!

Fig 1. Font changed!

In case something went wrong and you receive an error like this

UserWarning: findfont: Font family [‘sans-serif’] not found. Falling back to DejaVu Sans (prop.get_family(), self.defaultFamily[fontext]))

you need to check whether matplotlib is “seeing” your custom font. In order to do so, we can run in our notebook the following two lines of code

If your font is not in the list, you need to copy your custom font in the system library

and run again the commands from step 2 to 4.

Add a custom font without installing it

It is possible to use a custom font without installing it in your operating system.
First we download our font (again as an example we will use Comic Sans), and then we save it somewhere on the disk (path/to/font/).
Then we can run the following code to use our choosen font:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *