I'm trying to make a basic calculator in Tkinter and I'm having trouble with the text field and the number buttons. I'd like the button presses to show up in the Entry()
window, but I don't know how to deal with a StringVar
instance. It keeps telling me, that StringVar
has no .extend()
Attribute, even though it was used in a different post (older version maybe?). Right now all my button can do is .set()
the entry to '0' and nothing else.
Basically, I'd like the button presses to dynamically update my StringVar, as in extend the string from left to right. Optimally, I could use both the button as well as direct text input to update the StringVar
(Is that what trace is for?). Is StringVar
even the correct class for that? I'm very new to GUI programming so I don't know what to use.
import tkinter as tk
def N0(text):
text.set('0')
root = tk.Tk()
formula = tk.StringVar()
Num_bw = 0.08
Num_bh = 0.15
Num_bx = 0.01
Num_by = 0.01
Num_bx0 = 0
Num_by0 = 0
Num_bw_tol = 0.004
Num_bh_tol = 0.01
width, height = root.winfo_screenwidth(), root.winfo_screenheight()
width *= 0.5
height *= 0.5
r = width/height
root.geometry('%dx%d+0+0'%(width,height))
canvas = tk.Canvas(root,height=height,width=width,bg='#80dfff')
canvas.pack()
frame1 = tk.Frame(canvas,bg='#f2f2f2')
frame2 = tk.Frame(canvas,bg='#f2f2f2')
frame1.place(relx=0.03,rely=0.05,relwidth=0.94,relheight=0.2)
frame2.place(relx=0.07,rely=0.27,relwidth=0.86,relheight=0.68)
TextField = tk.Entry(frame1,bg='white',
textvariable=formula,
font=("Comic Sans MS", 15))
TextField.place(relx=0.01,rely=0.05,relwidth=0.98,relheight=0.9)
Num_0 = tk.Button(frame2,text='0',bg='#e6ffff',command=lambda:N0(formula))
Num_0.place(relx=Num_bw_tol*1 + Num_bx0 + Num_bw*1,
rely=Num_bh_tol*5 + Num_by0 + Num_bh*5,
relwidth=Num_bw,relheight=Num_bh)
root.mainloop()