Ttkbootstrap Meter widgets to show number of chars entered by user with colour zone bands #9
Function my_upd()
This function calculate the number of chars entered by the user inside the text widget. This value is displayed on the Label and our Meter m1 sets the amountused value to this number. Inside this function we will keep if elif condition checks to set the option bootstyle to different colors. There are 8 different colors are already avilable here is the list.
PRIMARY, SECONDARY, SUCCESS, INFO, WARNING, DANGER, LIGHT, DARK
def my_upd(value):
my_str = t1.get("1.0", "end-1c") # read the string
breaks = my_str.count("\n") # Number of line breaks
char_numbers = len(my_str) - breaks # Final number of chars
l2.config(text=str(char_numbers)) # display in Label
m1["amountused"] = char_numbers # connect to Meter
if char_numbers < 50:
m1["bootstyle"] = SUCCESS
elif char_numbers < 75:
m1["bootstyle"] = WARNING
elif char_numbers < 100:
m1["bootstyle"] = DANGER
if char_numbers >= 100: # to stop accepting char after limit
t1.delete("end-2c") # remove last char of text widget
import tkinter as tk
import ttkbootstrap as ttk
from ttkbootstrap.constants import *
# my_w = tk.Tk()
my_w = ttk.Window()
my_w.geometry("400x300") # width x height of the window
my_w.title("www.plus2net.com") # Adding a title
l1 = tk.Label(my_w, text="Your Data", width=10, font=20) # added one Label
l1.grid(row=0, column=0, padx=3, pady=10, columnspan=2)
t1 = tk.Text(my_w, height=3, width=40, bg="lightgreen", font=28) # text box
t1.grid(row=1, column=0, padx=10, columnspan=2)
l2 = tk.Label(my_w, text=0, font=22)
l2.grid(row=2, column=0, padx=5, pady=5)
m1 = ttk.Meter(
my_w,
amountused=0,
metersize=130,
meterthickness=20,
interactive=True,
bootstyle=SUCCESS,
)
m1.grid(row=2, column=1, padx=2, pady=5)
def my_upd(value):
my_str = t1.get("1.0", "end-1c") # read the string
breaks = my_str.count("\n") # Number of line breaks
char_numbers = len(my_str) - breaks # Final number of chars
l2.config(text=str(char_numbers)) # display in Label
m1["amountused"] = char_numbers # connect to Meter
if char_numbers < 50:
m1["bootstyle"] = SUCCESS
elif char_numbers < 75:
m1["bootstyle"] = WARNING
elif char_numbers < 100:
m1["bootstyle"] = DANGER
if char_numbers >= 100: # to stop accepting char after limit
t1.delete("end-2c") # remove last char of text widget
t1.bind("<KeyRelease>", my_upd) # Trigger on Key release event
my_w.mainloop() # Keep the window open