as plenty others I struggle with updating labels in the tkinter mainloop.
I've tried a lot, but I'm not even sure if the values are correctly updated outside the function.
Here is a minimum working example:
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
from tkinter import messagebox
from mainSIMstitchV2 import *
root = tk.Tk()
root.geometry("800x600")
root.title(" abc ")
tx1=tk.DoubleVar()
ty1=tk.DoubleVar()
angle1=tk.DoubleVar()
tx2=tk.DoubleVar()
ty2=tk.DoubleVar()
angle2=tk.DoubleVar()
def calculate ():
global tx1, ty1, angle1, tx2, ty2, angle2
tx1.set(tx1.get()+1.1)
print(tx1.get())
ty1.set(ty1.get()+1.1)
print(ty1.get())
return
button4 = tk.Button(root, text='Calculate', command = lambda: calculate())
button4.config( height = 2, width = 10 )
button4.place(x=200,y=220)
resultsframe = tk.Frame(root, width=735, height=200, background="red")
resultsframe.columnconfigure(0, weight=1)
resultsframe.columnconfigure(1, weight=2)
resultsframe.columnconfigure(2, weight=3)
resultsframe.place(x=30,y=300)
f2 = tk.Frame(resultsframe,width=245, height=200)
f2.grid(row=0, column=1)
t25 = tk.Label(f2,text="x:"+str(tx1.get()))
t25.config(text="x:"+str(tx1.get()))
t25.place(x=0,y=90)
t26 = tk.Label(f2,text="y:"+str(ty1.get()))
t26.place(x=0,y=110)
#root.update()
#resultsframe.update_idletasks()
root.after(200, root.update())
root.mainloop()
Please tell my how to achieve, that the label in the GUI are updated by the calculation.
Many thanks in advance!
If you use the textvariable
argument of the Label, the label will update to display the value of the variable whenever it changes. You could keep the DoubleVars as they are so that you can continue to do mathematical operations on them, and use StringVars as the textvariables of the Labels. In the calculate
function you can update the DoubleVars, and then use their new numerical values to update the StringVars.
import tkinter as tk
root = tk.Tk()
root.geometry("800x600")
root.title(" abc ")
tx1=tk.DoubleVar()
ty1=tk.DoubleVar()
tx1_str = tk.StringVar()
ty1_str = tk.StringVar()
tx1_str.set(f"x: {tx1.get()}")
ty1_str.set(f"y: {ty1.get()}")
def calculate ():
tx1.set(tx1.get()+1.1)
tx1_str.set(f"x: {tx1.get()}")
ty1.set(ty1.get()+1.1)
ty1_str.set(f"y: {ty1.get()}")
button4 = tk.Button(root, text='Calculate', command = lambda: calculate())
button4.config( height = 2, width = 10 )
button4.place(x=200,y=220)
resultsframe = tk.Frame(root, width=735, height=200, background="red")
resultsframe.place(x=30,y=300)
f2 = tk.Frame(resultsframe,width=245, height=200)
f2.grid(row=0, column=1)
t25 = tk.Label(f2,textvariable=tx1_str)
t25.place(x=0,y=90)
t26 = tk.Label(f2,textvariable=ty1_str)
t26.place(x=0,y=110)
root.mainloop()