e_v=tk.DoubleVar(master,value,name)
master
: (Optional)The variable is associated with, default value is parent window.value
:(Optional) We can set the initial value for the variable. name
: (Optional) Name given default is PY_VAR1
trace_add(self, mode, callback)
For an DoubleVar() we can check the different modes of this variable and trigger call back functions. This is the main advantage of using such variables.
b1 = tk.Button(my_w,text='Update',command=lambda:db1.set(10.34))
This triggers the trace_add() which used the callback function my_r() to print the value of the variable ( 10.34 ) to our console.
import tkinter as tk
from tkinter import *
my_w = tk.Tk()
my_w.geometry("300x100") # Size of the window
my_w.title("www.plus2net.com") # Adding a title
def my_r(*args):
print(db1.get()) # Print when variable changes.
db1 = tk.DoubleVar(my_w) # declare DoubleVar()
db1.set(5.1) # assign value to variable
b1 = tk.Button(my_w,text='Update',command=lambda:db1.set(10.34))
b1.grid(row=2,column=3,padx=20,pady=10)
db1.trace_add('write',my_r) # callback when data changes
my_w.mainloop()
Output
10.34
Use IntVar() for handling Integer data db1.set(10.34) # assign value to db1
print(db1.get()) # display the value assigned to db1
db1=tk.DoubleVar(value=5.1) # Assign value to db1
print(len(str(db1.get())))
import tkinter as tk
my_w = tk.Tk()
my_w.geometry("400x200") # Size of the window
e_v=tk.DoubleVar() # declare double varible
e_v.set(6.7) # assign the value to Double variable
e1=tk.Entry(my_w,textvariable=e_v,font=20)
e1.grid(row=0,column=0,padx=15,pady=15)
l1=tk.Label(my_w,text='Output',font=22,bg='yellow')
l1.grid(row=1,column=0,padx=15,sticky='ew')
def my_upd(*ags): # call back function
my_data=e_v.get() # reading value of Double var
l1.config(text=str(my_data)) # display in Label
e_v.trace_add('write',my_upd) # track the changes of Double variable
my_upd() # call the function to update the display
my_w.mainloop() # Keep the window open
AUTHOR
🎥 Join me live on YouTubePassionate about coding and teaching, I love sharing practical programming tutorials on PHP, Python, JavaScript, SQL, and web development. With years of experience, my goal is to make learning simple, engaging, and project-oriented. Whether you're a beginner or an experienced developer, I believe learning by doing is the best way to master coding. Let's explore the world of programming together!