Tuesday, April 22, 2025

Tkinter - Text Widget

In this tutorial we will talk about Tkinter Text Widget. Make sure that you can run this source, and than we will explain.

Please note, we are reading a textual file LICENCE.txt, which is located in Python install folder - this script must be in a folder where that txt file resides, too. You can set a path to some other txt file.

from tkinter import *
import tkinter.messagebox as mb
import os

top_win = Tk()
top_win.geometry("800x800")

file = open("LICENSE.txt", "r")

t = Text(top_win, padx = 20, pady = 20, width = 50, height = 20,
         cursor = "dot", relief = RIDGE, bd = 10, bg = "lightyellow",
         fg = "red", selectbackground = "yellow", selectforeground = "black",
         font = "Verdana")

for x in file.read():
    t.insert(END, x)

file.close()
t.pack(side = TOP, anchor = NW)
top_win.mainloop()

This is line that will open LICENCE.txt for reading:

file = open("LICENSE.txt", "r")

And this is source for Text Widget. We have padding set, width and height set, type of cursor, type of relief, border width, background color, text color, font type is Verdana, and background and foreground color set when we select part of text:

t = Text(top_win, padx = 20, pady = 20, width = 50, height = 20,
         cursor = "dot", relief = RIDGE, bd = 10, bg = "lightyellow",
         fg = "red", selectbackground = "yellow", selectforeground = "black",
         font = "Verdana")

With for loop we are reading txt file content. Otherwise you will not see any text on screen, just borders and colors:

for x in file.read():
    t.insert(END, x)

This line will close file:

file.close()

As with other widgets we must pack our text section, and at the end of script is standard mainloop:

t.pack(side = TOP, anchor = NW)
top_win.mainloop()

Consider watching corresponding YouTube tutorial on Tkinter Text Widget.

This is end of this tutorial and YT playlist on Tkinter, and you have a lot of other Python tutorials on this site and WebDevPro channel.

Learn More:

Free Python Programming Course
Python Examples
Python How To
Python Modules 

YouTube WebDevPro Tutorials

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...