Home > Net >  Print a placeholder in bold within a sentence, using tags. AttributeError: 'str' object ha
Print a placeholder in bold within a sentence, using tags. AttributeError: 'str' object ha

Time:09-01

If I select City in the combobox, I would like to print London placeholder in bold. London only in bold, the rest of the sentence not in bold. I've never used tags, so I'm having a hard time, sorry for my difficulty. I would like to obtain:

LONDON Phrase1, Phrase2, Phrase3.

I get the error: AttributeError: 'str' object has no attribute 'tag_config'

How to solve? I would like to try to maintain this code structure, or at least a similar structure.

from tkinter import ttk
import tkinter as tk
from tkinter import *

root = tk.Tk()
root.geometry("300x200")

combobox=ttk.Combobox(root, width = 16)
combobox.place(x=15, y=10)
combobox['value'] = ["City", "Other"]


textbox = tk.Text(root,width=20,height=4)
textbox.place(x=15, y=50)

def function1():
    if combobox.get() == "City":
        city = "London" #city = diz[sel_city]["City"]
        city_start = city.upper()
        city_start.tag_config(font=("Verdana", 14, 'bold'))


    def function2():
        text =  f"{city_start} Phrase1, Phrase2, Phrase3"
                
        textbox.delete(1.0,END)     
        textbox.insert(tk.END, text) #.format(allenat_random=allenat_random, variable_random=variable_random))

    function2()


Button = Button(root, text="Print", command=function1)
Button.pack()
Button.place(x=15, y=130)
 
root.mainloop()

CodePudding user response:

Note that .tag_config() should be called on instance of Text widget, i.e. textbox in your case. Also the first argument of .tag_config() should be a tag name.

Then .tag_add() should be used to apply the configured effect on the text.

Below is the modified function1():

def function1():
    if combobox.get() == "City":
        city = "London" #city = diz[sel_city]["City"]
        city_start = city.upper()
        textbox.tag_config('city', font=("Verdana", 14, 'bold')) ### added tag argument


    def function2():
        text =  f"{city_start} Phrase1, Phrase2, Phrase3"

        textbox.delete(1.0,END)
        textbox.insert(tk.END, text) #.format(allenat_random=allenat_random, variable_random=variable_random))

        ### search city_start
        idx = textbox.search(city_start, 1.0)
        ### apply effect on city_start
        textbox.tag_add('city', idx, f'{idx} {len(city_start)}c')

    function2()

And the result:

enter image description here

  • Related