简体   繁体   English

Python Tkinter标签公式

[英]Python tkinter label formulas

how can I make a label with a formula and whenever I change the value in entry, does it automatically change the value in the label? 如何用公式制作标签,每当更改条目中的值时,它是否会自动更改标签中的值? As if it were excel cells with formulas. 好像是带有公式的excel单元格一样。 And in case it would have to be invisible (without content) while the entry is empty. 并且在条目为空的情况下必须不可见(无内容)。

import tkinter as tk

root = tk.Tk()
ent1 = tk.Entry(root)
lab1 = tk.Label(root,text='Price')
ent2 = tk.Entry(root)
lab2 = tk.Label(root,text='Quantity')
lab3 = tk.Label(root,text='') #lab3 formula = float(ent1.get()) * int(ent2.get())

lab1.pack() 
ent1.pack()
lab2.pack()
ent2.pack()
lab3.pack()

Use the trace method to execute a function when a variable changes. 变量更改时,请使用trace方法执行函数。

import tkinter as tk

def update(*args):
    try:
        output_var.set(price_var.get() * quantity_var.get())
    except (ValueError, tk.TclError):
        output_var.set('invalid input')

root = tk.Tk()

lab1 = tk.Label(root,text='Price')
price_var = tk.DoubleVar()
price_var.trace('w', update) # call the update() function when the value changes
ent1 = tk.Entry(root, textvariable=price_var)

lab2 = tk.Label(root,text='Quantity')
quantity_var = tk.DoubleVar()
quantity_var.trace('w', update)
ent2 = tk.Entry(root, textvariable=quantity_var)

output_var = tk.StringVar()
lab3 = tk.Label(root, textvariable=output_var) #lab3 formula = float(ent1.get()) * int(ent2.get())

lab1.pack()
ent1.pack()
lab2.pack()
ent2.pack()
lab3.pack()

root.mainloop()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM