Download Article
Download Article
So you have installed the Python 2.7 or 3.1 in your computer and you want to learn Python programming? The default font size of Python shell is so small that your eyes may get affected by looking so much timely. Here are the steps to increase the font size of Python shell.
-
1
Open the Python shell. Open the start menu from start menu or double clicking the shortcut. the window looks like this.
-
2
Click on the options from the top menu bar, and then click on Configure IDLE. The new window opens automatically and looks like this.
Advertisement
-
3
Change font size. Now in the fonts/tabs tab there will be option to change the font type/name and below it font size.
Advertisement
Add New Question
-
Question
How do you change the font size in Python shell while working on an Apple Mac?
Open the Python shell. Then, in the menu bar, under «Python» (directly to the right of the Apple icon), you will find «Preferences». Under this, you will find the «Font/Tabs» option, and you can change the font size according to your preference.
-
Question
What is the default font in Python?
Bryan Hadland
Community Answer
The default is Courier New.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Thanks to all authors for creating a page that has been read 140,340 times.
Is this article up to date?
wikiHow Tech Help Pro:
Level up your tech skills and stay ahead of the curve
Let’s go!
Download Article
Download Article
So you have installed the Python 2.7 or 3.1 in your computer and you want to learn Python programming? The default font size of Python shell is so small that your eyes may get affected by looking so much timely. Here are the steps to increase the font size of Python shell.
-
1
Open the Python shell. Open the start menu from start menu or double clicking the shortcut. the window looks like this.
-
2
Click on the options from the top menu bar, and then click on Configure IDLE. The new window opens automatically and looks like this.
Advertisement
-
3
Change font size. Now in the fonts/tabs tab there will be option to change the font type/name and below it font size.
Advertisement
Add New Question
-
Question
How do you change the font size in Python shell while working on an Apple Mac?
Open the Python shell. Then, in the menu bar, under «Python» (directly to the right of the Apple icon), you will find «Preferences». Under this, you will find the «Font/Tabs» option, and you can change the font size according to your preference.
-
Question
What is the default font in Python?
Bryan Hadland
Community Answer
The default is Courier New.
Ask a Question
200 characters left
Include your email address to get a message when this question is answered.
Submit
Advertisement
Thanks for submitting a tip for review!
About This Article
Thanks to all authors for creating a page that has been read 140,340 times.
Is this article up to date?
wikiHow Tech Help Pro:
Level up your tech skills and stay ahead of the curve
Let’s go!
Improve Article
Save Article
Improve Article
Save Article
Prerequisite: Python GUI – tkinter
Python provides a Tkinter module for GUI (Graphical User Interface). In this article, we are going to see how to set text font in Tkinter.
Text Widget is used where a user wants to insert multi-line text fields. In this article, we are going to learn the approaches to set the font inserted in the text fields of the text widget. It can be done with different methods.
Method 1: Using a tuple and .configure( ) method.
Approach :
- Import the tkinter module.
- Create a GUI window.
- Create our text widget.
- Create a tuple containing the specifications of the font. But while creating this tuple, the order should be maintained like this, (font_family, font_size_in_pixel, font_weight). Font_family and font_weight should be passed as a string and the font size as an integer.
- Parse the specifications to the Text widget using .configure( ) method.
Below is the implementation of the above approach
Python3
import
tkinter
root
=
tkinter.Tk()
root.title(
"Welcome to GeekForGeeks"
)
root.geometry(
"400x240"
)
sample_text
=
tkinter.Text( root, height
=
10
)
sample_text.pack()
Font_tuple
=
(
"Comic Sans MS"
,
20
,
"bold"
)
sample_text.configure(font
=
Font_tuple)
root.mainloop()
Output :
Method 2: Setting the font using the Font object of tkinter.font
Approach:
- Import the Tkinter module.
- Import Tkinter font.
- Create the GUI window
- Create our text widget.
- Create an object of type Font from tkinter.font module. It takes in the desired font specifications(font_family, font_size_in_pixel , font_weight) as a constructor of this object. This is that specified object that the text widget requires while determining its font.
- Parse the Font object to the Text widget using .configure( ) method.
Below is the implementation of the above approach:
Python3
import
tkinter
import
tkinter.font
root
=
tkinter.Tk()
root.title(
"Welcome to GeekForGeeks"
)
root.geometry(
"918x450"
)
sample_text
=
tkinter.Text( root, height
=
10
)
sample_text.pack()
Desired_font
=
tkinter.font.Font( family
=
"Comic Sans MS"
,
size
=
20
,
weight
=
"bold"
)
sample_text.configure(font
=
Desired_font)
root.mainloop()
Output:
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
import tkinter as tk from tkinter import * #main window root = Tk() #title of the window root.title("Tkinter Font Size") #adding a label l = Label(root, text="This is a sample line with font size 15.", width=40, height=5, font=('Times New Roman', 15, 'bold')) l.pack() root.mainloop()
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
Recommended Read: Tkinter Font Class Tutorial
import tkinter as tk from tkinter import * import tkinter.font as tkFont #main window root = tk.Tk() #title of the window root.title("Tkinter Font Size") #creating a font object fontObj = tkFont.Font(size=28) #adding a label l = Label(root, text="This is a sample line with font size 28.", width=40, height=5, font=fontObj) l.pack() root.mainloop()
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
import tkinter as tk from tkinter import * from tkinter.font import Font #creating a custom class class cl: def __init__(self, master) -> None: self.master = master #setting the font size to be 40 self.customFont = Font(size=40) Label(self.master, text="Font size in the custom class is 40.", font=self.customFont).pack() #end of custom class if __name__ == "__main__": #main window root = tk.Tk() #title of the window root.title("Tkinter Font Size") #adding a label l = Label(root, text="This is a sample line with default font size.", width=40, height=5) l.pack() #calling our class object customSize = cl(root) root.mainloop()
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.
Стилизация
Шрифты
Последнее обновление: 24.09.2022
Имена шрифтов
Ряд виджетов, например, Label или Text, поддерживают установку шрифта через параметр font.
Каждая платформа может определять свои специфические шрифты. Но также библиотека Tk по умолчанию включает ряд именнованных шрифтов, которые могут использоваться на
различных компонентах графического интерфейса и которые доступны на всех платформах:
-
TkDefaultFont: шрифт по умолчанию, который применяется, если для виджета явным образом не определен шрифт
-
TkTextFont: шрифт по умолчанию, который применяется для виджетов Entry, Listbox и ряда других
-
TkFixedFont: шрифт с фиксированной шириной
-
TkMenuFont: шрифт для пунктов меню
-
TkHeadingFont: шрифт для заголовков в Listbox и в таблицах
-
TkCaptionFont: шрифт для строки статуса в окнах
-
TkSmallCaptionFont: шрифт малого размера для диалоговых окон
-
TkIconFont: шрифт для подписей к иконкам
-
TkTooltipFont: шрифт для высплывающих окон
В принципе мы можем использовать эти шрифты не только в любых виджетах:
ttk.Label(text="Hello World", font="TkTextFont")
Tk также предоставляет дополнительный набор именнованных шрифтов, которые определены только на определенных платформах. Для их получения можно использовать
функцию names() из пакета tkinter.font
:
from tkinter import font for font_name in font.names(): print(font_name)
Например, на Windows мы получим следующий набор:
fixed oemfixed TkDefaultFont TkMenuFont ansifixed systemfixed TkHeadingFont device TkTooltipFont defaultgui TkTextFont ansi TkCaptionFont system TkSmallCaptionFont TkFixedFont TkIconFont
В данном случае выводятся и платформа-независимые, и платформо-специфичные шрифты, например, «system».
ttk.Label(text="Hello World", font="system")
Определение шрифта
За определение шрифта в Tkinter отвечает класс Font из модуля tkinter.font
. Он принимет следующие параметры:
-
name
: имя шрифта -
family
: семейство шрифтов -
size
: высота шрифта (в точках при положительном значении или в пикселях при негативном значении) -
weight
: вес шрифта. Принимает значенияnormal
(обычный) илиbold
(жирный) -
slant
: наклон. Принимает значенияroman
(обычный) илиitalic
(наклонный) -
underline
: подчеркивание. Принимает значенияTrue
(с подчеркиванием) илиFalse
(без подчеркивания) -
overstrike
: зачеркивание. Принимает значенияTrue
(с зачеркиванием) илиFalse
(без зачеркивания)
Для получения всех доступных семейств шрифтов на текущей платформе можно использовать функцию families() из модуля tkinter.font
from tkinter import font for family in font.families(): print(family)
Пример применения шрифтов:
from tkinter import * from tkinter import ttk from tkinter import font root = Tk() root.title("METANIT.COM") root.geometry("250x200") font1 = font.Font(family= "Arial", size=11, weight="normal", slant="roman", underline=True, overstrike=True) label1 = ttk.Label(text="Hello World", font=font1) label1.pack(anchor=NW) font2 = font.Font(family= "Verdana", size=11, weight="normal", slant="roman") label2 = ttk.Label(text="Hello World", font=font2) label2.pack(anchor=NW) root.mainloop()
Также можно использовать определение шрифта в виде строки:
from tkinter import * from tkinter import ttk root = Tk() root.title("METANIT.COM") root.geometry("250x200") label1 = ttk.Label(text="Hello World", font="Arial 11 normal roman") label1.pack(anchor=NW) label2 = ttk.Label(text="Hello World", font="Verdana 11 normal roman") label2.pack(anchor=NW) root.mainloop()
Например, в определении "Arial 11 normal roman"
, применяется семейство шрифта Arial, высота 11 единиц, нежирный шрифт без наклона.
Метод configure
виджета Tkinter Text
задаёт свойства Text
, подобно шрифту текста. Шрифт font
может быть как tuple
типом, так и объектом Tkinter Font
.
import tkinter as tk
root = tk.Tk()
root.geometry("400x240")
textExample=tk.Text(root, height=10)
textExample.pack()
textExample.configure(font=("Courier", 16, "italic"))
root.mainloop()
textExample.configure(font=("Courier", 16, "italic"))
Он устанавливает шрифт Courier
, курсив с размером 16
.
Также мы могли бы установить шрифт с помощью объекта font
модуля tkFont
.
import tkinter as tk
import tkinter.font as tkFont
root = tk.Tk()
root.geometry("400x240")
textExample=tk.Text(root, height=10)
textExample.pack()
fontExample = tkFont.Font(family="Arial", size=16, weight="bold", slant="italic")
textExample.configure(font=fontExample)
root.mainloop()
fontExample = tkFont.Font(family="Arial", size=16, weight="bold", slant="italic")
Преимущество использования объекта Font
вместо шрифта tuple
заключается в том, что один и тот же объект Font
может быть присвоен различным виджетам и программно обновлен методом Font.configure
. Все виджеты, имеющие один и тот же объект Font
, будут обновлены в новом стиле font
.
fontExample.configure(weight='normal')
Он обновляет вес fontExample
, чтобы быть normal
.
Для вашего удобства мы перечислили все доступные семейства шрифтов в Tkinter (Tkinter 3, Windows OS). Вы также можете перечислить семейства шрифтов в вашей рабочей среде со следующими кодами,
import tkinter as tk
import tkinter.font as tkFont
print(list(tkFont.families()))
[
'System',
'Terminal',
'Fixedsys',
'Modern',
'Roman',
'Script',
'Courier',
'MS Serif',
'MS Sans Serif',
'Small Fonts',
'Marlett',
'Arial',
'Arabic Transparent',
'Arial Baltic',
'Arial CE',
'Arial CYR',
'Arial Greek',
'Arial TUR',
'Arial Black',
'Bahnschrift Light',
'Bahnschrift SemiLight',
'Bahnschrift',
'Bahnschrift SemiBold',
'Bahnschrift Light SemiCondensed',
'Bahnschrift SemiLight SemiConde',
'Bahnschrift SemiCondensed',
'Bahnschrift SemiBold SemiConden',
'Bahnschrift Light Condensed',
'Bahnschrift SemiLight Condensed',
'Bahnschrift Condensed',
'Bahnschrift SemiBold Condensed',
'Calibri',
'Calibri Light',
'Cambria',
'Cambria Math',
'Candara',
'Candara Light',
'Comic Sans MS',
'Consolas',
'Constantia',
'Corbel',
'Corbel Light',
'Courier New',
'Courier New Baltic',
'Courier New CE',
'Courier New CYR',
'Courier New Greek',
'Courier New TUR',
'Ebrima',
'Franklin Gothic Medium',
'Gabriola',
'Gadugi',
'Georgia',
'Impact',
'Ink Free',
'Javanese Text',
'Leelawadee UI',
'Leelawadee UI Semilight',
'Lucida Console',
'Lucida Sans Unicode',
'Malgun Gothic',
'@Malgun Gothic',
'Malgun Gothic Semilight',
'@Malgun Gothic Semilight',
'Microsoft Himalaya',
'Microsoft JhengHei',
'@Microsoft JhengHei',
'Microsoft JhengHei UI',
'@Microsoft JhengHei UI',
'Microsoft JhengHei Light',
'@Microsoft JhengHei Light',
'Microsoft JhengHei UI Light',
'@Microsoft JhengHei UI Light',
'Microsoft New Tai Lue',
'Microsoft PhagsPa',
'Microsoft Sans Serif',
'Microsoft Tai Le',
'Microsoft YaHei',
'@Microsoft YaHei',
'Microsoft YaHei UI',
'@Microsoft YaHei UI',
'Microsoft YaHei Light',
'@Microsoft YaHei Light',
'Microsoft YaHei UI Light',
'@Microsoft YaHei UI Light',
'Microsoft Yi Baiti',
'MingLiU-ExtB',
'@MingLiU-ExtB',
'PMingLiU-ExtB',
'@PMingLiU-ExtB',
'MingLiU_HKSCS-ExtB',
'@MingLiU_HKSCS-ExtB',
'Mongolian Baiti',
'MS Gothic',
'@MS Gothic',
'MS UI Gothic',
'@MS UI Gothic',
'MS PGothic',
'@MS PGothic',
'MV Boli',
'Myanmar Text',
'Nirmala UI',
'Nirmala UI Semilight',
'Palatino Linotype',
'Segoe MDL2 Assets',
'Segoe Print',
'Segoe Script',
'Segoe UI',
'Segoe UI Black',
'Segoe UI Emoji',
'Segoe UI Historic',
'Segoe UI Light',
'Segoe UI Semibold',
'Segoe UI Semilight',
'Segoe UI Symbol',
'SimSun',
'@SimSun',
'NSimSun',
'@NSimSun',
'SimSun-ExtB',
'@SimSun-ExtB',
'Sitka Small',
'Sitka Text',
'Sitka Subheading',
'Sitka Heading',
'Sitka Display',
'Sitka Banner',
'Sylfaen',
'Symbol',
'Tahoma',
'Times New Roman',
'Times New Roman Baltic',
'Times New Roman CE',
'Times New Roman CYR',
'Times New Roman Greek',
'Times New Roman TUR',
'Trebuchet MS',
'Verdana',
'Webdings',
'Wingdings',
'Yu Gothic',
'@Yu Gothic',
'Yu Gothic UI',
'@Yu Gothic UI',
'Yu Gothic UI Semibold',
'@Yu Gothic UI Semibold',
'Yu Gothic Light',
'@Yu Gothic Light',
'Yu Gothic UI Light',
'@Yu Gothic UI Light',
'Yu Gothic Medium',
'@Yu Gothic Medium',
'Yu Gothic UI Semilight',
'@Yu Gothic UI Semilight',
'HoloLens MDL2 Assets',
'BIZ UDGothic',
'@BIZ UDGothic',
'BIZ UDPGothic',
'@BIZ UDPGothic',
'BIZ UDMincho Medium',
'@BIZ UDMincho Medium',
'BIZ UDPMincho Medium',
'@BIZ UDPMincho Medium',
'Meiryo',
'@Meiryo',
'Meiryo UI',
'@Meiryo UI',
'MS Mincho',
'@MS Mincho',
'MS PMincho',
'@MS PMincho',
'UD Digi Kyokasho N-B',
'@UD Digi Kyokasho N-B',
'UD Digi Kyokasho NP-B',
'@UD Digi Kyokasho NP-B',
'UD Digi Kyokasho NK-B',
'@UD Digi Kyokasho NK-B',
'UD Digi Kyokasho N-R',
'@UD Digi Kyokasho N-R',
'UD Digi Kyokasho NP-R',
'@UD Digi Kyokasho NP-R',
'UD Digi Kyokasho NK-R',
'@UD Digi Kyokasho NK-R',
'Yu Mincho',
'@Yu Mincho',
'Yu Mincho Demibold',
'@Yu Mincho Demibold',
'Yu Mincho Light',
'@Yu Mincho Light',
'DengXian',
'@DengXian',
'DengXian Light',
'@DengXian Light',
'FangSong',
'@FangSong',
'KaiTi',
'@KaiTi',
'SimHei',
'@SimHei',
'Ubuntu',
'Raleway',
'Ubuntu Condensed',
'Ubuntu Light'
]
Tkinter actually has a variety of ways in which we may change the font type and size. Tkinter has several built in fonts, which can complicate things, especially when you realize that Each widget only uses one of these fonts. However, this also gives us the option to individually change the font type and size for different types of widgets.
We’ll start off with a general way of changing the font size and type that effects everything in the tkinter window.
Technique 1
The following code will only change the Font.
import tkinter as tk root = tk.Tk() root.option_add('*Font', '19') root.geometry("200x150") label = tk.Label(root, text = "Hello World") label.pack(padx = 5, pady = 5) root.mainloop()
The following code changes only the font type. Tip:
import tkinter as tk root = tk.Tk() root.option_add('*Font', 'Times') root.geometry("200x150") label = tk.Label(root, text = "Hello World") label.pack(padx = 5, pady = 5) root.mainloop()
Tip: If you want a list of font families, you can use the following code. It will return a list of different font types.
from tkinter import Tk, font root = Tk() print(font.families())
Finally, you can change both simultaneously by writing both at the same time.
import tkinter as tk root = tk.Tk() root.option_add('*Font', 'Times 19') root.geometry("200x150") label = tk.Label(root, text = "Hello World") label.pack(padx = 5, pady = 5) root.mainloop()
Note, however, that option_add
only affects widgets created after you’ve called option_add
, so you need to do it before creating any other widgets.
Technique 2
Here narrow down our area of effect from the whole tkinter program to certain segments of it. As mentioned earlier, tkinter has several built in fonts which different widgets use. We can change each one of these individually.
import tkinter as tk import tkinter.font as tkFont root = tk.Tk() print(tkFont.names())
('fixed', 'oemfixed', 'TkDefaultFont', 'TkMenuFont', 'ansifixed', 'systemfixed', 'TkHeadingFont', 'device', 'TkTooltipFont', 'defaultgui', 'TkTextFont', 'ansi', 'TkCaptionFont', 'system', 'TkSmallCaptionFont', 'TkFixedFont', 'TkIconFont')
Above we can notice several font types like TkHeadingFont
and TkMenuFont
. These appear to be the fonts that determine the font type and size for headings and Menu’s respectively. Let’s try to change the TkDefaultFont
. Any widget that uses the TkDefaultFont
type will automatically change to the new settings.
import tkinter as tk import tkinter.font as tkFont root = tk.Tk() root.geometry("200x150") def_font = tk.font.nametofont("TkDefaultFont") def_font.config(size=24) label = tk.Label(root, text = "Hello World") label.pack(padx = 5, pady = 5) root.mainloop()
The tricky part however is figuring out which widgets are affected by which Font types. Due to a lack of material, this information is currently unavailable. Though you are free to search for it on your own.
This marks the end of the change font type and size in Tkinter article. Any suggestions or contributions for CodersLegacy are more than welcome. Any questions can be asked in the comments section below.
See more Tkinter related tit bits below.
How to improve Tkinter screen resolution?
How to prevent resizing in Tkinter Windows?
Using Lambda with Tkinter “command” option