I'm trying to add two integers dynamically with tkinter. My idea is to get the sum after typing in a integer. My idea:
import tkinter as tk
root = tk.Tk()
root.geometry("600x100")
v = tk.IntVar()
w = tk.IntVar()
eingabefeld = tk.Entry(master=root, textvariable = v)
eingabefeld.place(x=80, y=40)
eingabefeld = tk.Entry(master=root, textvariable = w)
eingabefeld.place(x=320, y=40)
label = tk.Label(master=root, textvariable = v)
label.place(x=80, y=80)
label = tk.Label(master=root, textvariable = str(int(v.get()) int(w.get())))
label.place(x=320, y=80)
root.mainloop()
If start the program the result of the addition is not presented in the label. What is missing here?
CodePudding user response:
You aren't using the textvariable
option correct. The value passed to that option needs to be an instance of one of the tkinter variable objects (StringVar
, IntVar
, etc). You can't just pass an expression to it.
You need to write a function that calculates the result and sets the value of this variable. The function can then be called from a button, or you can set a trace on the variable and update it every time the value changes. You'll have to make sure to take care of the case where one of the values you're trying to add is not a valid integer.
CodePudding user response:
Try this for newbie entry level. I only used one label and add function. using Python 3.11.0rc1.
import tkinter as tk
root = tk.Tk()
var1 = tk.IntVar()
t1 = tk.Entry(root, textvariable=var1)
t1.pack()
var2 = tk.IntVar()
t2 = tk.Entry(root, textvariable=var2)
t2.pack()
result = tk.IntVar()
l = tk.Label(root, textvariable=result)
l.pack()
#ll = tk.Label(root, textvariable=result)
#ll.pack()
# Put trace callbacks on the Entry DoubleVars
def set_label(name, index, mode):
result.set(int(var1.get()) int(var2.get()))
var1.trace('w', set_label)
var2.trace('w', set_label)
#var1.trace('w', set_label)
#var2.trace('w', set_label)
# Setting the vars will trigger the trace
var1.set(0)
var2.set(0)
root.mainloop()