automatic update entry calculation tkinter with trace add

Solutions on MaxInterview for automatic update entry calculation tkinter with trace add by the best coders in the world

showing results for - "automatic update entry calculation tkinter with trace add"
Alexy
09 Apr 2018
1import Tkinter as tk
2
3root = tk.Tk()
4temp_f_number = tk.DoubleVar()
5temp_c_number = tk.DoubleVar()
6
7tk.Label(root, text="F").grid(row=0, column=0)
8tk.Label(root, text="C").grid(row=0, column=1)
9
10temp_f = tk.Entry(root, textvariable=temp_f_number)
11temp_c = tk.Entry(root, textvariable=temp_c_number)
12
13temp_f.grid(row=1, column=0)
14temp_c.grid(row=1, column=1)
15
16update_in_progress = False
17
18def update_c(*args):
19    global update_in_progress
20    if update_in_progress: return
21    try:
22        temp_f_float = temp_f_number.get()
23    except ValueError:
24        return
25    new_temp_c = round((temp_f_float - 32) * 5 / 9, 2)
26    update_in_progress = True
27    temp_c_number.set(new_temp_c)
28    update_in_progress = False
29
30def update_f(*args):
31    global update_in_progress
32    if update_in_progress: return
33    try:
34        temp_c_float = temp_c_number.get()
35    except ValueError:
36        return
37    new_temp_f = round(temp_c_float * 9 / 5 + 32, 2)
38    update_in_progress = True
39    temp_f_number.set(new_temp_f)
40    update_in_progress = False
41
42temp_f_number.trace("w", update_c)
43temp_c_number.trace("w", update_f)
44
45root.mainloop()