Перейти к содержимому

Как увеличить шрифт в питоне

  • автор:

How to set the font size in Tkinter?

Tkinter Font Size Featured Image

In this article, we are going to learn how to change the font size of the text in Tkinter. Font size refers to how large the characters displayed on the screen are. It is crucial to use proper font size in order to gain the reader’s attention wherever needed. So let’s see the different ways using which we can change the font size of text using Tkinter.

Method 1: Changing Tkinter font size using the font as a tuple

Output:

Font Size Tuple Output

Font Size Tuple Output

In the above code, we have created a very basic GUI and added a label to it. Label widgets have an inbuilt property of font(‘font family’, size, ‘font style’). Font acts as a parameter in the code above. If not mentioned explicitly, the parameters will have their default values. In the above code, we have only used the size property and set the size to 15.

Method 2: Changing tkinter font size using the font as an object

Output:

Font Size Object Output

Font Size Object Output

Here, we have created an object of the Font class named fontObj and set the font size to 28. Later, in the label, we assigned the value of parameters for the font to be equal to the font object (fontObj) and hence, in the output, the font size is 28. In addition to size, we can also mention the font family and style as required.

Method 3: Using changing fonts using a custom class

Output:

Font Size Custom Class Output

Font Size Custom Class Output

In the above example, we have defined a custom class (cl), inside which we have a constructor where we assign the font size to 40. A label is also created with the font parameter being equal to the customFont.

In the main function, we first created a label with no explicit mention of the size of the text. Hence, it has the default size. After this, we call the cl class by creating its object customSize. On creating a new instance or object, the label with font size 40 is also displayed in the output along with the default size label.

Every time a new instance of the class is created, the label with font size 40 will be displayed as it is a part of the constructor of the class here. We can also set the font family and style inside the class itself.

Summary

In this way, we have understood how to change the font size in Tkinter in multiple ways. It is an easy topic to understand and implement. Please check out our other Tkinter tutorials here.

Как увеличить шрифт в питоне

Начал осваивать python 3.3
Работаю на 15 дюймовом экране.
Интересует как увеличить размер вводимого текста, а то он слишком мелкий.
Устают глаза при длительной работе.

#2 Окт. 6, 2012 19:29:34

Размер текста

Настроить разрешение экрана/размер шрифта в редакторе?

#3 Окт. 6, 2012 20:12:21

Размер текста

Именно, интересует изменение размера шрифта в самом редакторе IDLE.
Установил python под mac. Перекопал все системные настройки, но ничего не меняется.

#4 Окт. 6, 2012 20:28:03

Размер текста

options -> configure IDLE -> Fonts/Tabs -> Size
нет такого?

#5 Окт. 6, 2012 20:36:29

Размер текста

К сожалению такого нет.

Прикреплённый файлы:
attachmentScreen Shot 2012-10-06 at 21.32.42.png (78,0 KБ)

#6 Окт. 6, 2012 20:43:50

Размер текста

может на яблоко тыкнуть или IDLE?
у меня так вот

Прикреплённый файлы:
attachmentidle.png (57,3 KБ)

#7 Окт. 6, 2012 21:00:21

Размер текста

sergeek, благодарю за помощь! настроил!
всё перепробовал, а в idle/preferences не зашёл.)
теперь можно и дальше продолжать осваивать.

Основные настройки IDLE Python

Среда разработки IDLE Shell достаточно проста, если сравнивать с другими средствами разработки, такими как Delphi или Visual Studio, или со средствами разработки на Python от сторонних разработчиков. Однако и её тоже не помешает настроить под свои предпочтения.

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

Настройки IDLE выполняются в окне настроек, которое вызывается через меню

OPTIONS — CONFIGURE IDLE

Окно настроек содержит пять вкладок (страниц):

Окно настроек IDLE: вкладка ШРИФТЫ И ТАБУЛЯЦИЯ

Рис. 1-3-1. Окно настроек IDLE: вкладка ШРИФТЫ И ТАБУЛЯЦИЯ

Шрифты и табуляция

На первой вкладке FONTS/TABS (шрифты/табуляция) можно выбрать шрифт и установить размер табуляции.

Для исходных кодов лучше выбирать моноширинный шрифт (шрифт с одинаковой шириной всех символов). Я предпочитаю Courier New.

Ниже (под списком шрифтов) можно выбрать размер шрифта, а также сделать его жирным.

Справа предварительный просмотр выбранного шрифта.

Также вы можете установить размер табуляции (то есть на какое количество пробелов будет перемещаться курсор при нажатии на клавишу ТАВ). Значение по умолчанию равно 4. Но я всегда ставлю 2, чтобы код не расползался в ширину при наличии множества вложенных блоков.

Подсветка синтаксиса

Я работаю в разных средах разработки с разными языками. И практически в каждой среде разработки свои предпочтения по цвету ключевых слов, строк, цифр и т.п. Но мне не нравится, когда подсветка синтаксиса отличается от привычной. Поэтому, когда я устанавливаю какую-то новую IDE, то я первым делом настраиваю цвета текста в редакторе исходного кода.

Если это ваш первый язык программирования, то можете здесь ничего не менять (вам пока без разницы), можете привыкнуть и к стандартным цветам.

Но если захотите изменить, то переходите на вкладку HIGHLIGHTS (подсветка), и устанавливайте цвета, какие вам больше нравятся:

Окно настроек IDLE: вкладка ПОДСВЕТКА СИНТАКСИСА

Рис. 1-3-2. Окно настроек IDLE: вкладка ПОДСВЕТКА СИНТАКСИСА

Если в группе SELECT вы выберите “a Built-in Theme” (встроенные темы), то установится подсветка по умолчанию. В этом случае можно будет выбрать одну из трёх предустановленных тем:

  • IDLE Classic
  • IDLE Dark
  • IDLE New

Если же вы выберите “a Custom Theme” (пользовательская тема), то можете установить свои цвет текста и цвет фона для любого доступного элемента (для ключевых слов, для чисел, для строк и т.п.). Вы можете создать несколько собственных тем.

После того, как вы вдоволь наиграетесь с выбором цветов, надо щёлкнуть по кнопке APPLY, чтобы изменения вступили в силу. Если вы создали свою тему, то её нужно сохранить с помощью кнопки “Save as New Custom Theme”.

Цвета изменяются отдельно для текста (Foreground) и для фона (Background). Для изменения текста или фона должен быть выбран соответствующий переключатель (см. рис. 1-3-2).

Чтобы установить цвет для элемента — щёлкните по кнопке с надписью “Choose Color For” и в открывшемся окне установите нужный цвет.

Под этой кнопкой расположена кнопка выбора элемента, а надпись на этой кнопке указывает на название выбранного элемента. Если щёлкнуть по этой кнопке, то появится список доступных элементов.

Чтобы выбрать элемент для изменения цвета, можно также щёлкнуть по элементу в окне предварительного просмотра.

Остальные три вкладки рассматривать не будем — для начинающих они пока не нужны.

How to make IDLE window more readable? Font too small for me to see

On the top menu, choose Options , then Configure IDLE . The Fonts/Tabs tab will be displayed. There is a Size button. Click on it and select a bigger size than the default of 10. At present, this only only affects the font in Shell, editor, and output windows, but that is the main issue for me.

EDIT: correct Options menu entry as suggested by Nathan Wailes. IDLE Preferences was once the title of the resulting dialog, but it is now Settings .

Terry Jan Reedy's user avatar

For Mac Python 3.9, Go to Idle -> Preferences -> Fonts/Tabs Option.

    The Overflow Blog
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Как увеличить шрифт в питоне

Tkinter Label is used to display one or more lines, it can also be used to display bitmap or images. In this article, we are going to change the font-size of the Label Widget. To create Label use following:

Syntax: label = Label(parent, option, …)

Parameters:
parent: Object of the widget that will display this label, generally a root object
text: To display one or more lines of text.
image: To display a static image
compound: To display both Text and Image. It accepts TOP, BOTTOM, LEFT, RIGHT, CENTER. For example, if you write compound=TOPimage will displayed to the top of Text.

We can do this using different methods:

Method 1: By using Label’s font property.

How to Change the Tkinter Label Font Size?

Tkinter Label is used to display one or more lines, it can also be used to display bitmap or images. In this article, we are going to change the font-size of the Label Widget. To create Label use following:

Syntax: label = Label(parent, option, …)

Parameters:
parent: Object of the widget that will display this label, generally a root object
text: To display one or more lines of text.
image: To display a static image
compound: To display both Text and Image. It accepts TOP, BOTTOM, LEFT, RIGHT, CENTER. For example, if you write compound=TOPimage will displayed to the top of Text.

We can do this using different methods:

Method 1: By using Label’s font property.

Python3

Output:

Method 2: By using Style class. In this method, we will use our custom style otherwise all the Label widgets will get the same style.

Python3

Output:

Note: In the above method, TLabel is the name of the default style. So if you want to create your own style name then always use below syntax

my_style_name.default_style_name

Example:
New.TButton # To override Button Widget’s styles
My.TLabel # To override Label Widget’s Styles
Abc.TEntry # To override Entry Widget’s Styles

If you use only the default style name then it will apply to all the corresponding widgets i.e if I use TLabel instead of My.TLabel then both the label will have font-size of 25. And importantly, if you use the default style name then you don’t need to provide style property.

Extra: Changing font size using the Default Style Name.

Python3

Notice in the above program that we have not provided style or font property to any of the Label still both of them got the same font-size and same font-family.

Output:

Method 3: By using the Font class. In this method, we will create a Font object and then use this to change Font style of any widget. Benefit of this

Font class consist of following property:
root: Object of toplevel widget.
family: The font family name as a string.
size: The font height as an integer in points.
weight: ‘bold’/BOLD for boldface, ‘normal’/NORMAL for regular weight.
slant: ‘italic’/ITALIC for italic, ‘roman’/ROMAN for unslanted.
underline: 1/True/TRUE for underlined text, 0/False/FALSE for normal.
overstrike: 1/True/TRUE for overstruck text, 0/False/FALSE for normal.

How to increase the font size of a Text widget?

There are several ways to specify a font: the simplest is a tuple of the form (family, size, style) .

Bryan Oakley's user avatar

    The Overflow Blog
Related
Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.8.2.43556

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

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

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