Python Tkinter Entry() Calculations - python

I am currently trying to build a GUI calculator using python with the help of tkinter. I have managed to set up all of my buttons and they interact with my entry() bar when I press the button (e,g: Press button 5 and 5 appears into the entry()).
The only thing left to do is actually perform the mathematical equations that appear in the entry(). For example, if I enter 5 + 5 * 2 into the entry bar, how would I make the answer appear into the entry() after it's updated? So basically all I'm asking is someone to help me make this happen!
I have provided the code below and a screenshot of the calculator. Also please don't report this as a duplicate or flag this question as a post, (I'm reasking this question because I got no help on my last one so please help a young python programmer out!). Also I'm asking you not to provide me with links because I've read every possible link on tkinter there is to read and still have no clue what I'm doing.
Here is my code:
import sys
from tkinter import *
from PIL import Image, ImageTk
#ACTIONS:
def clear():
#Action: Clears the entry().
txtDisplay.delete(0,END);
return;
def update_Entry(inputValue):
#Updates the entry when a button is pressed.
currentText = num1.get();
update = num1.set(currentText + inputValue);
#Parent Window.
root = Tk();
root.title('Calculator ++ [1.7.2]');
root.geometry('350x450');
#Main entry.
num1 = StringVar();
txtDisplay = Entry(root, textvariable = num1, relief=RIDGE, bd = 10, width=33, insertwidth = 1, font = 40, justify=RIGHT);
txtDisplay.place(x=15, y=10);
txtDisplay.focus();
print(txtDisplay.get())
#Buttons:
zeroButton = Button(root, text='0', width=20, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('0'));
zeroButton.place(x=17,y=382);
oneButton = Button(root, text='1', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('1'));
oneButton.place(x=17, y=302);
twoButton = Button(root, text='2', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('2'));
twoButton.place(x=100, y=302);
threeButton = Button(root, text='3', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('3'));
threeButton.place(x=182, y=302);
fourButton = Button(root, text='4', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('4'));
fourButton.place(x=17, y=222);
fiveButton = Button(root, text='5', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('5'));
fiveButton.place(x=100, y=222);
sixButton = Button(root, text='6', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('6'));
sixButton.place(x=182, y=222);
sevenButton = Button(root, text='7', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('7'));
sevenButton.place(x=17, y=142);
eightButton = Button(root, text='8', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('8'));
eightButton.place(x=100, y=142);
ninthButton = Button(root, text='9', width=8, height=3, bg='LightBlue', fg='red', command=lambda:update_Entry('9'));
ninthButton.place(x=182, y=142);
decimalButton = Button(root, text='.', width=8, height=3, bg='powder blue', command=lambda:update_Entry('.'));
decimalButton.place(x=182, y=382);
equalButton = Button(root, text='=', width=8, height=8, bg='Lightgreen', command=lambda:update_Entry('='));
equalButton.place(x=264, y=307);
plusButton = Button(root, text='+', width=8, height=3, bg='gray', command=lambda:update_Entry('+'));
plusButton.place(x=264, y=222);
minusButton = Button(root, text='-', width=8, height=3, bg='gray', command=lambda:update_Entry('-'));
minusButton.place(x=264, y=142);
multiplyButton = Button(root, text='x', width=8, height=3, bg='gray', command=lambda:update_Entry('*'));
multiplyButton.place(x=264, y=66);
divideButton = Button(root, text='รท', width=8, height=3, bg='gray', command=lambda:update_Entry('/'));
divideButton.place(x=182, y=66);
clearButton = Button(root, text='Clear (CE)', width=20, height=3, command = clear, bg='Orange');
clearButton.place(x=17, y=66);
#Locks the parent windows size.
root.maxsize(350,450);
root.minsize(350,450);
#Parent window's background color:
root.configure(background = 'black');
root.mainloop();
Screenshot:

For something this simple, try having this as the command for your equalButton:
def evaluate():
currentText = num1.get()
try:
num1.set(str(eval(currentText)))
except SyntaxError:
num1.set('<ERROR>')

Related

How to remove 2 buttons by pressing one?

I want to remove the buttons "play" and "help" by pressing just on button "play". How can I do that? I need that the button "play" destroy himself and in addition destroy the button "help"
This is my code:
from tkinter import *
import tkinter.messagebox
from random import *
window = Tk()
window.title("Simon")
window.geometry("300x200")
label = Label(window, text="Simon Game!", font=("Ariel", 80),
bg="CadetBlue3")
label.pack()
window.configure(bg="CadetBlue3")
def destroy(button):
def inner():
button.destroy()
return inner
def click_help_button():
tkinter.messagebox.showinfo("Instructions", "The device
creates a series of tones and lights and requires a user to
repeat the sequence. If the user succeeds, the series becomes
progressively longer and more complex. Once the user fails, the
game is over")
help_btn = Button(window, width=12, height=2, text="Help",
bg="grey",font=("Ariel", 18), command=click_help_button)
help_btn.pack(side='bottom')
help_btn.place(x=800, y=150)
start_btn = Button(window, width=12, height=2, text="Play",
bg="grey", font=("Ariel", 18), command=destroy(help_btn))
start_btn.pack(pady=10)
start_btn.place(x=525, y=150)
start_btn.config(command=destroy(start_btn))
red_btn = Button(window, width=35, height=15, bg='red')
red_btn.place(x=495, y=270)
green_btn = Button(window, width=35, height=15, bg='green')
green_btn.place(x=750, y=270)
blue_btn = Button(window, width=35, height=15, bg='blue')
blue_btn.place(x=495, y=495)
yellow_btn = Button(window, width=35, height=15, bg='yellow')
yellow_btn.place(x=750, y=495)
window.mainloop()
Thanks to those who help!
I would make a click_play_button function
def click_play_button():
start_btn.destroy()
help_btn.destroy()
And call on it when pressing the play button
start_btn = Button(window, width=12, height=2, text="Play",
bg="grey", font=("Ariel", 18), command=click_play_button)
start_btn.pack(pady=10)
start_btn.place(x=525, y=150)
Below also worked...
def destroy(button):
button.destroy()
def click_help_button():
tkinter.messagebox.showinfo("Instructions", "The device")
help_btn = Button(window, width=12, height=2, text="Help",
bg="grey", font=("Ariel", 18), command=click_help_button)
help_btn.pack(side='bottom')
help_btn.place(x=800, y=150)
start_btn = Button(window, width=12, height=2, text="Play",
bg="grey", font=("Ariel", 18), command=lambda: [destroy(help_btn), destroy(start_btn)])
start_btn.pack(pady=10)
start_btn.place(x=525, y=150)
red_btn = Button(window, width=35, height=15, bg='red')
red_btn.place(x=495, y=270)
green_btn = Button(window, width=35, height=15, bg='green')
green_btn.place(x=750, y=270)
blue_btn = Button(window, width=35, height=15, bg='blue')
blue_btn.place(x=495, y=495)
yellow_btn = Button(window, width=35, height=15, bg='yellow')
yellow_btn.place(x=750, y=495)
window.mainloop()

NOT using pack still getting error: cannot use geometry manager grid inside . which already has slaves managed by pack

So I know we don't mix .pack and .grid and in my simple code I haven't packed but am using .grid but still getting error.
On the bottom, I have attached the error image that I am getting along with the code
Code:
`from tkinter import *
root = Tk()
root.title("Calculator")
# root.geometry('600x500')
def add():
print("works")
input_num1 = Entry(root)
input_num1.pack()
button_0 = Button(root, text="0", command=add)
button_1 = Button(root, text="1", command=add)
button_2 = Button(root, text="2", command=add)
button_3 = Button(root, text="3", command=add)
button_4 = Button(root, text="4", command=add)
button_5 = Button(root, text="5", command=add)
button_6 = Button(root, text="6", command=add)
button_7 = Button(root, text="7", command=add)
button_8 = Button(root, text="8", command=add)
button_9 = Button(root, text="9", command=add)
button_add = Button(root, text="+", command=add)
button_minus = Button(root, text="-", command=add)
button_div = Button(root, text="/", command=add)
button_multi = Button(root, text="X", command=add)
button_0.grid(row=4, column=0)
button_1.grid(row=3, column=0)
button_2.grid(row=3, column=1)
button_3.grid(row=3, column=2)
button_4.grid(row=2, column=0)
button_5.grid(row=2, column=1)
button_6.grid(row=2, column=2)
button_7.grid(row=1, column=0)
button_8.grid(row=1, column=1)
button_9.grid(row=1, column=2)
button_add.grid(row=1, column=3)
button_minus.grid(row=1, column=4)
button_div.grid(row=2, column=3)
button_multi.grid(row=2, column=4)
root.mainloop()
`
Error:
enter image description here
As it has already been noted, you are indeed using pack().
Try commenting out the offending line (or remove it completely) and setting input_num1 to occupy row 4, column 5 in the grid, like this:
input_num1 = Entry(root)
#input_num1.pack() <----------------
input_num1.grid(row=4, column=5) <----------------

Does anyone know why my tkinter buttons aren't rendering?

This is for a python project on GitHub where I'm making a GUI for a Magic 8 Ball simulation. I cant seem to use the .pack() function or my window just loads forever without ever instantiating.
When created
When I click a button the text appears
window = Tk()
window.configure(bg="black")
window.title("Magic 8 Ball")
Label(window, text="Ask the Magic 8 Ball the question on your mind or enter X to exit: ", bg="black", fg="white")\
.grid(row=0, column=0)
# Create entry box to type question
entrybox = Entry(window, width=30, bg="white")
entrybox.grid(row=1, column=0)
# Create output box at below buttons
output = Text(window, bg="white", fg="black", width=40, height=5)
output.grid(row=4, column=0)
# Create 4 button: Ask, Clear, Play Again, Quit
button_frame = Frame(window)
button_frame.configure(bg="black")
button_frame.grid(row=2, column=0)
#button_frame.pack(fill=X, side=BOTTOM)
Button(button_frame, text="Ask", width=10, bg="black", fg="white", command=click).grid(row=2, column=0)
Button(button_frame, text="Clear", width=10, command=clear).grid(row=2, column=1)
Button(button_frame, text="Play Again", width=10,command=repeat).grid(row=3, column=0)
Button(button_frame, text="Quit", width=10, command=close).grid(row=3, column=1)
window.mainloop()
I think we will need more specifications about your OS and python version. I ran it on Python 3.5.0 and Windows 10 with the result:
So I do not think it is an error in your code. I did have to add in all the functions and import you were missing so what I ran ended up looking like:
from tkinter import *
window = Tk()
def click():
print('click')
def clear():
print('clear')
def repeat():
print('repeat')
def close():
print('close')
window.configure(bg="black")
window.title("Magic 8 Ball")
Label(window, text="Ask the Magic 8 Ball the question on your mind or enter X to exit: ", bg="black", fg="white")\
.grid(row=0, column=0)
# Create entry box to type question
entrybox = Entry(window, width=30, bg="white")
entrybox.grid(row=1, column=0)
# Create output box at below buttons
output = Text(window, bg="white", fg="black", width=40, height=5)
output.grid(row=4, column=0)
# Create 4 button: Ask, Clear, Play Again, Quit
button_frame = Frame(window)
button_frame.configure(bg="black")
button_frame.grid(row=2, column=0)
#button_frame.pack(fill=X, side=BOTTOM)
Button(button_frame, text="Ask", width=10, bg="black", fg="white", command=click).grid(row=2, column=0)
Button(button_frame, text="Clear", width=10, command=clear).grid(row=2, column=1)
Button(button_frame, text="Play Again", width=10,command=repeat).grid(row=3, column=0)
Button(button_frame, text="Quit", width=10, command=close).grid(row=3, column=1)
window.mainloop()

How to update Labels in tkinter?

I'm trying to create a program in where you put a word in a box, press add, and this word goes to a list, which is also displayed on the right side. When I press the forward button the first thing on the list is deleted. Problem is I can't get the labels to update when I press the buttons / edit the list.
from tkinter import *
root = Tk()
root.title('Speakers List')
root.minsize(800, 600)
speakers = ['none']
spe = speakers[0]
def add():
if spe == 'none':
speakers.insert(0, [s])
e.delete(0, END)
spe.config(text=speakers[0])
else:
speakers[-2] = [s]
e.delete(0, END)
spe.config(text=speakers[0])
return
def forward():
if len(speakers) is 0:
return
else:
del speakers[0]
spe.config(text=speakers[0])
return
entry = StringVar()
e = Entry(root, width=30, font=("Arial", 20), textvariable=entry)
e.grid(row=0, sticky=W)
s = e.get()
button1 = Button(root, padx=10, pady=10, bd=5, text='Add', fg='black', command=add)
button1.grid(row=0, column=1)
button2 = Button(root, padx=10, pady=10, bd=5, text='Next', fg='black', command=forward)
button2.grid(row=1, column=1)
n = Label(root, font=("Arial", 35), bd=2, text=spe)
n.grid(row=1, sticky=W)
listdisplay = Label(root, font=('Arial', 20), text=speakers)
listdisplay.grid(row=0, column=10)
root.mainloop()
Is this the sort of thing you were looking for ?
from tkinter import *
root = Tk()
root.title('Speakers List')
root.minsize(800, 600)
speakers = ['50']
spe = speakers[0]
def add():
entry=e.get()
speakers.append(entry)
listdisplay.config(text=speakers)
return
def forward():
if len(speakers) is 0:
return
else:
del speakers[0]
listdisplay.config(text=speakers)
spe=speakers[0]
n.config(text=spe)
return
entry = StringVar()
e = Entry(root, width=30, font=("Arial", 20), textvariable=entry)
e.grid(row=0, sticky=W)
s = e.get()
button1 = Button(root, padx=10, pady=10, bd=5, text='Add', fg='black',command=add)
button1.grid(row=0, column=1)
button2 = Button(root, padx=10, pady=10, bd=5, text='Next', fg='black',command=forward)
button2.grid(row=1, column=1)
n = Label(root, font=("Arial", 35), bd=2, text=spe)
n.grid(row=1, sticky=W)
listdisplay = Label(root, font=('Arial', 20), text=speakers)
listdisplay.grid(row=0, column=10)
root.mainloop()
If so:
You create a list and then you use the append function to add an item to it. The rest was pretty much right.

grid_remove on an Entry widget

Im new to Tkinter and am trying to build a simple GUI using grid manager which upon the push of button1, button2 appears along with an adjacent entry box. If you then press button2 the entry box and button2 dissapear. Below is a slice from the GUI code, the button dissapears but the entry box does not:
import Tkinter
from Tkinter import *
master = Tk()
CreateTestButton = Button(master, text="Create Test", command = CreateTest, fg="red", bg="white", font="Helvetica 10 bold")
CreateTestButton.grid(column=7, row=1)
def CreateTest():
TestEntry = Entry(master, text="", width = 100).grid(row=4,columnspan=6)
Label(self, text="Enter Test Name:").grid(row=3, column=0)
SaveTestButton = Button(master, text="Save to database", command=saveTest, fg="green", bg="white", font="Helvetica 10 bold")
SaveTestButton.grid(row=4, column=5)
def saveTest():
SaveTestButton.grid_remove()
TestEntry.grid_remove() #ERROR
mainloop()
How is one to remove entry boxes using grid manager in Tkinter? And other widgets for that matter I will also be needing to remove a list box, labels and widgets uppon a button click or event.
Regards,
Daniel
grid return nothing; By executing TestEntry = Entry(..).grid(...), TestEntry become None instead of Entry object.
Replace following line:
TestEntry = Entry(self, text="", width = 100).grid(row=4,columnspan=6)
with:
TestEntry = Entry(self, text="", width = 100)
TestEntry.grid(row=4,columnspan=6)
Complete code
from Tkinter import *
def CreateTest():
def saveTest():
SaveTestButton.grid_remove()
TestEntry.grid_remove() #ERROR
TestEntry = Entry(master, text="", width = 100)
TestEntry.grid(row=4,columnspan=6)
Label(master, text="Enter Test Name:").grid(row=3, column=0)
SaveTestButton = Button(master, text="Save to database", command=saveTest, fg="green", bg="white", font="Helvetica 10 bold")
SaveTestButton.grid(row=4, column=5)
master = Tk()
CreateTestButton = Button(master, text="Create Test", command = CreateTest, fg="red", bg="white", font="Helvetica 10 bold")
CreateTestButton.grid(column=7, row=1)
mainloop()

Categories