Python tkinter标签公式

2024-10-02 22:24:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用公式制作标签?每当我更改条目中的值时,它是否会自动更改标签中的值?就像excel单元格里有公式一样。以防在条目为空时它必须是不可见的(没有内容)。你知道吗

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

Tags: textget条目root标签labelpacktk
1条回答
网友
1楼 · 发布于 2024-10-02 22:24:09

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

相关问题 更多 >