0

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()
J.Doe
  • 224
  • 1
  • 4
  • 19
  • _"even though it was used in a different post "_. Sounds interesting. Can you provide a link to that post? – Kevin Nov 26 '19 at 19:11
  • https://stackoverflow.com/questions/16373887/how-to-set-the-text-value-content-of-an-entry-widget-using-a-button-in-tkinter Aaaaaand I need glasses. It's appied to Entry... – J.Doe Nov 26 '19 at 19:12
  • @J.Doe Read about [The Variable Classes (StringVar)](http://effbot.org/tkinterbook/variable.htm) – stovfl Nov 26 '19 at 19:36

1 Answers1

0

I'm not a Tkinter guru myself, but maybe you can create a function that will update the "calculator screen" on each button press like this

def updateButton(num, text):
    text.set(text.get() + str(num))

And call the function as the onclick for each of the calculator buttons, just like you did for the N0 function

Lior Dahan
  • 682
  • 2
  • 7
  • 19