Home > Blockchain >  Print the text in bold and smaller size in Tkinter
Print the text in bold and smaller size in Tkinter

Time:07-24

I would like to print the variable x, so the text "Example1" in bold. Also I would like to print the text variable y with smaller size: only variable y with smaller size.

There were examples on the web, but not like in my case, because I use f "and {xxx}.

Here is an example of an executable code that you can use in case you want to help me. Thank you

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

root = tk.Tk()
root.geometry("400x150")

textbox = tk.Text(root,width=48,height=4)
textbox.place(x=1, y=5)
  
x = "Example1"
y = "Example2"
              
def print():
        
    text = f"A sentence that contains the variable: {x}" \
           f"\n \n This must possess smaller size: {y} " 
           
    textbox.insert(tk.END, text)

button2 = Button(root, text="Print", command = print)
button2.pack()
button2.place(x=15, y=100)

CodePudding user response:

Try taking a look here: https://tkdocs.com/tutorial/text.html. I don't know if this can help you. However you have to create a function to specify x and y.

CodePudding user response:

I believe there is no direct way to format the variables because in the Text widget it's all just one string. You could use indices with the tag_add and tag_configure methods to format specific text. For example in this case, the last word of the 1st line is bold, and the last word of the 3rd line (note, the 2nd line is empty due to the extra \n) is supposed to be smaller.

In the below code 1.end-1c wordstart means go to the end of line 1 (which is a \n) minus 1 character (which is the last letter of x), then go to the starting character of that word. 1.end-1c wordend means go to the last character of x. Likewise for y as well.

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

root = tk.Tk()
root.geometry("400x150")

textbox = tk.Text(root,width=48,height=4)
textbox.place(x=1, y=5)
  
x = "Example1"
y = "Example2"
              
def print():
        
    text = f"A sentence that contains the variable: {x}" \
           f"\n \n This must possess smaller size: {y} " 
           
    textbox.insert(tk.END, text)

    textbox.tag_add("setbold", "1.end-1c wordstart", "1.end-1c wordend")
    textbox.tag_configure("setbold", font="Arial 13 bold")
    textbox.tag_add("setsmall", "3.end-1c wordstart", "3.end-1c wordend")
    textbox.tag_configure("setsmall", font="Arial 5")

button2 = Button(root, text="Print", command = print)
button2.pack()
button2.place(x=15, y=100)
  • Related