Python Forum
[Tkinter] manipulation of string in Text widget
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] manipulation of string in Text widget
#1
hello everybody
I'm trying to create a simple text editor in Tkinter, to help building HTML pages.
I just write things in the text area, and use buttons to add tags, like <h1>.
[Image: Captura-de-tela-de-2020-02-15-11-44-44.png]
this is what I have so far:
from tkinter import *
root = Tk()

def addHeader():
	a = main_text.get(Tk.SEL_FIRST, Tk.SEL_LAST)


main_text = Text(root).grid(row=0, column=0, rowspan=6)

b_header = Button(root, text ="Header", command=addHeader).grid(row=0, column=1, padx=2, pady=2)
spin_header = Spinbox(root, from_=1, to=6,  width=5).grid(row=0, column=2, padx=2, pady=2)

b_ref = Button(root, text ="Referência").grid(row=1, column=1, padx=2, pady=2)
spin_href = Spinbox(root, from_=0, to=9999,  width=5).grid(row=1, column=2, padx=2, pady=2)

name_label = Label(root, text="Nome do Arquivo: ").grid(row=2, column=1, columnspan=2, padx=2, pady=2)
name_entry = Entry(root).grid(row=3, column=1, columnspan=2, padx=2, pady=2)
b_save = Button(root, text ="Finalizar e Salvar").grid(row=4, column=1, columnspan=2, padx=2, pady=2)

root.mainloop()
what I want to achieve is, when the b_header is pressed, html tags are added around whatever is selected in the text area (ie, add <h1> at the beggining of the selected text and </h1> at the end). if nothing is selected, just add the tags in the cursor position.
but currently I get this error when I press the button (the function addHeader is not working):
Error:
Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.7/tkinter/__init__.py", line 1705, in __call__ return self.func(*args) File "teste.py", line 5, in addHeader a = main_text.get(Tk.SEL_FIRST, Tk.SEL_LAST) AttributeError: 'NoneType' object has no attribute 'get'
any ideas on how to make it work?
thanks in advance Big Grin
Reply
#2
This book: https://github.com/manash-biswal/Python-...otshot.pdf
Has the best coverage of text widget manipulation I've ever seen. Worth taking look,

**NOTE** I'd suggest purchasing a copy

Here: https://www.packtpub.com/application-dev...nt-hotshot
or here: https://www.amazon.com/Tkinter-GUI-Appli...B00G8YAUX4
The one on GitHub may be copyright infringement
Reply
#3
thanks, I found the answer!

the problem was this line:
b_header = Button(root, text ="Header", command=addHeader).grid(row=0, column=1, padx=2, pady=2)
doing it in a single line made the b_header return 'NoneType'. I just had to change it to:
b_header = Button(root, text ="Header", command=addHeader)
b_header.grid(row=0, column=1, padx=2, pady=2)
and of course I changed a lot of things. here is what I have so far, if it interests anyone. it's almost finished, to be honest.

from tkinter import *
from tkinter import filedialog
import re
root = Tk()

def addHeader():
	if main_text.tag_ranges("sel"):
		t = main_text.get("sel.first", "sel.last")
		main_text.delete("sel.first", "sel.last")
	else:
		t = ""
	t = "<h" + spin_header.get() + ">" + t + "</h" + spin_header.get() + ">"
	main_text.insert(INSERT, t)
	
def addParagraph():
	if main_text.tag_ranges("sel"):
		t = main_text.get("sel.first", "sel.last")
		main_text.delete("sel.first", "sel.last")
	else:
		t = ""
	t = "<p>" + t + "</p>"
	main_text.insert(INSERT, t)

def addPeriod():
	if main_text.tag_ranges("sel"):
		t = main_text.get("sel.first", "sel.last")
		main_text.delete("sel.first", "sel.last")
	else:
		t = ""
	t = t + "<sup>[" + spin_period.get() + "]</sup>"
	main_text.insert(INSERT, t)
	
def addOL():
	if main_text.tag_ranges("sel"):
		t = main_text.get("sel.first", "sel.last")
		main_text.delete("sel.first", "sel.last")
	else:
		t = ""
	t = "<ol>\n" + t + "\n</ol>"
	main_text.insert(INSERT, t)
	
def addUL():
	if main_text.tag_ranges("sel"):
		t = main_text.get("sel.first", "sel.last")
		main_text.delete("sel.first", "sel.last")
	else:
		t = ""
	t = "<ul>\n" + t + "\n</ul>"
	main_text.insert(INSERT, t)
	
def addLI():
	if main_text.tag_ranges("sel"):
		t = main_text.get("sel.first", "sel.last")
		main_text.delete("sel.first", "sel.last")
	else:
		t = ""
	t = "<li>" + t + "</li>"
	main_text.insert(INSERT, t)
	
def addReference():
	filename = filedialog.askopenfilename(initialdir = "../").replace(" ", "%20")
	main_text.insert(INSERT, "<a href=\"" + filename + "#page=3\">Nome</a>")

def finalizeArticle():
	t = """<!DOCTYPE html>
<html lang="pt-br">
<head>
	<title>""" + name_entry.get() + """</title>
	<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>""" + name_entry.get() + """</h1>
<div class="menu">\n"""
	headers2 = re.findall(re.compile("<h2>(.+?)</h2>"), main_text.get("1.0",END))
	headers2_links = []
	for h in headers2:
		headers2_links.append(h.replace(" ", "_"))
		t = t + "\t<a href=#" + h.replace(" ", "_") + ">" + h + "</a>\n"
	t = t + "<a href=#Referências>Referências</a>\n</div>\n\n" + main_text.get("1.0", END) + """<br><br>
</body>
</html> """
	for i in range(len(headers2)):
		t = t.replace("<h2>" + headers2[i], "<h2 id=" + headers2_links[i] + ">" + headers2[i])
	file = open(name_entry.get().lower().replace(" ", "_") + ".html", "w")
	file.write(t)
	file.close()

main_text = Text(root)#, width=140, height=40)
main_text.grid(row=0, column=0, rowspan=8)
main_text.insert("1.0", "\n\n<h2 id=Referências>Referências</h2>\n<ol>\n\n</ol>")

b_header = Button(root, text ="Header", command=addHeader)
b_header.grid(row=0, column=1, padx=2, pady=2)
spin_header = Spinbox(root, from_=1, to=6,  width=5, textvariable=DoubleVar(value=2))
spin_header.grid(row=0, column=2, padx=2, pady=2)

b_paragr = Button(root, text ="Parágrafo", command=addParagraph)
b_paragr.grid(row=1, column=1, columnspan=2, padx=2, pady=2)

b_period = Button(root, text ="Frase", command=addPeriod)
b_period.grid(row=2, column=1, padx=2, pady=2)
spin_period = Spinbox(root, from_=0, to=9999,  width=5)
spin_period.grid(row=2, column=2, padx=2, pady=2)

b_ol = Button(root, text ="<ol>", command=addOL)
b_ol.grid(row=3, column=1, padx=2, pady=2)
b_ul = Button(root, text ="<ul>", command=addUL)
b_ul.grid(row=3, column=2, padx=2, pady=2)
b_li = Button(root, text ="<li>", command=addLI)
b_li.grid(row=4, column=1, columnspan=2, padx=2, pady=2)

b_ref = Button(root, text ="Adicionar Referência", command=addReference)
b_ref.grid(row=5, column=1, columnspan=2, padx=2, pady=2)

name_label = Label(root, text="Nome do Artigo: ").grid(row=6, column=1, columnspan=2, padx=2, pady=2)
name_entry = Entry(root)
name_entry.grid(row=7, column=1, columnspan=2, padx=2, pady=2)
b_save = Button(root, text ="Finalizar e Salvar", command=finalizeArticle)
b_save.grid(row=8, column=1, columnspan=2, padx=2, pady=2)

root.mainloop()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: could not convert string to float: '' fron Entry Widget russellm44 5 490 Mar-06-2024, 08:42 PM
Last Post: russellm44
  [Tkinter] The Text in the Label widget Tkinter cuts off the Long text in the view malmustafa 4 4,665 Jun-26-2022, 06:26 PM
Last Post: menator01
  [Tkinter] Text widget inert mode on and off rfresh737 5 3,782 Apr-19-2021, 02:18 PM
Last Post: joe_momma
  Line numbers in Text widget rfresh737 3 5,309 Apr-15-2021, 12:30 PM
Last Post: rfresh737
  tkinter text widget word wrap position chrisdb 6 7,446 Mar-18-2021, 03:55 PM
Last Post: chrisdb
  [Tkinter] Get the last entry in my text widget Pedroski55 3 6,294 Jul-13-2020, 10:34 PM
Last Post: Pedroski55
  How to place global tk text widget in class or on canvas puje 1 2,281 Jul-04-2020, 09:25 AM
Last Post: deanhystad
  [Tkinter] Paste Operation not working in Text Widget Code_Enthusiast 1 2,907 Sep-11-2019, 08:49 PM
Last Post: Larz60+
  how to insert image into Text widget Tkinter atlass218 5 9,926 Apr-17-2019, 05:28 AM
Last Post: atlass218
  [Tkinter] Lock Text Widget height Oxylium 3 4,162 Feb-14-2019, 10:13 PM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020