Tkinter:更新主循环中的标签

问题描述 投票:0回答:1

和其他很多人一样,我在 tkinter 主循环中更新标签方面遇到了困难。

我已经尝试了很多,但我什至不确定这些值是否在函数外部正确更新。

这是一个最小的工作示例:

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()

请告诉我如何实现,通过计算更新GUI中的标签。

提前非常感谢!

python user-interface tkinter
1个回答
0
投票

如果您使用标签的

textvariable
参数,则每当变量发生变化时,标签就会更新以显示变量的值。您可以保持 DoubleVars 不变,以便可以继续对它们进行数学运算,并使用 StringVars 作为标签的文本变量。在
calculate
函数中,您可以更新 DoubleVars,然后使用它们的新数值来更新 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()
© www.soinside.com 2019 - 2024. All rights reserved.