Python Forum

Full Version: Finishing GUI calculator project
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I wrote this code but i need help with finishing it, i cant get the button to complete the equation, im net to python and coding btw..
from tkinter import *
  
master = Tk()

master.title("Calculator")

#Labels
Label(master, text="Number 1:").grid(row=0, column=0)
Label(master, text="Number 2:").grid(row=1, column=0)
Label(master, text="Operator:").grid(row=2, column=0)

#Enter
num1 = Entry(master).grid(row=0, column=1)
num2 = Entry(master).grid(row=1, column=1)
operator = Entry(master).grid(row=2, column=1)
enter = Button(master, text="Enter").grid(row=3, column=1)


times = (num1 *  num2)
minus = (num1 -  num2)
divide = (num1 /  num2)
plus = (num1 +  num2)

if enter == true:
    if operator == "*":
        print(times)
    if operator == "-":
        print(minus)
    if operator == "/":
        print(divide)
    if operator == "+":
        print(plus)

master.mainloop()
you should use buttons for entry. You've already got tkinter installed, and buttons will solve a lot of issues.
Also, if you use a class, you won't have to worry about callbacks.
There's a lot missing in your code, and structure isn't correct.
You should look at the docs at least for the widgets that you are using here: https://docs.python.org/3/library/tk.html
for example, you must use either a 'command' attribute, or a bind instruction in order for the button to execute a command.
And you need to 'get' the text value of the Entry widget.

Here's a simple Button example
import tkinter as tk

root = tk.Tk()
root.geometry('100x100+50+50')

def clicked():
    print('Button clicked')

def make_button():
    # notice there is no () after clicked because we want reference to clicked routine,
    # and if () were added, it would be executed immediately
    btn = tk.Button(root, text='Push Me', command=clicked)
    btn.pack()

make_button()

root.mainloop()
You can bound an Entry to a tkinter variable to get the value in Entry. For example:

num1var = tk.DoubleVar()
num1 = Entry(master, variable=num1var).grid(row=0, column=1)
then to get the value
entry1 = num1var.get()
This requires using tkinter variables. It does not work with ordinary Python variables. The tkinter variable classes are: StringVar, IntVar, DoubleVar, and BooleanVar.
If your new to code then use a GUI Designer like (https://visualtk.com/) or (https://labdeck.com/python/). I recommend https://labdeck.com/python/ as it's more consistent. They can both generate the GUIs into Python so this will definitely save you time.