I am trying to make a simple calculator, I am using an entry widget to display the numbers, and buttons to type the numbers.
When I type numbers using the buttons, (btn1, btnadd, btn2), it should be like this in the entry widget 1+2 instead it is like this 2+1
I know mathematically they are the same, but it won't be the case with division or subtraction
My code:
from tkinter import *
root = Tk()
def add():
entered.insert(0, '+')
def num_1():
entered.insert(0, 1)
def num_2():
entered.insert(0, 2)
entered = Entry(root)
entered.pack()
btn1 = Button(root, text='1', command=num_1).pack()
btn2 = Button(root, text='2', command=num_2).pack()
btn_add = Button(root, text='+', command=add).pack()
root.mainloop()
P.S I tried using pyautogui write function but the code was lagging and slow.
I'm new, hope this will help you!! ^^ Also, this is "smallest to change" solution: you just need to replace a few characters.
from tkinter import *
root = Tk()
def add():
entered.insert(END, '+') # END instead of 0, it adds '+' at the end
def num_1():
entered.insert(END, 1) # END instead of 0, it adds 1 at the end
def num_2():
entered.insert(END, 2) # END instead of 0, it adds 2 at the end
entered = Entry(root)
entered.pack()
btn1 = Button(root, text='1', command=num_1).pack()
btn2 = Button(root, text='2', command=num_2).pack()
btn_add = Button(root, text='+', command=add).pack()
root.mainloop()
Thank you for making a fun to answer question! :D
So the problem was that entered.insert(0, '+') the 0 is where its going to place the + so every time you were pushing the button you were placing the 1 and the 2 and the + at position 0
from tkinter import *
root = Tk()
i= 0
def add():
global i
entered.insert(i, '+')
i += 1
def num_1():
global i
entered.insert(i, 1)
i += 1
def num_2():
global i
entered.insert(i, 2)
i += 1
entered = Entry(root)
entered.pack()
btn1 = Button(root, text='1', command=num_1).pack()
btn2 = Button(root, text='2', command=num_2).pack()
btn_add = Button(root, text=' +', command=add).pack()
root.mainloop()
so now you have the global i that will change the position of the placement...
Ok this is how to delete
from asyncio.windows_events import NULL
from os import remove
from tkinter import *
root = Tk()
i= 0
def add():
global i
entered.insert(i, '+')
i += 1
def num_1():
global i
entered.insert(i, 1)
i += 1
def num_2():
global i
entered.insert(i, 2)
i += 1
def delete():
global i
i -= 1
entered.delete(i)
entered = Entry(root)
entered.pack()
btn1 = Button(root, text='1', command=num_1).pack()
btn2 = Button(root, text='2', command=num_2).pack()
btn_add = Button(root, text=' +', command=add).pack()
btn_rem = Button(root,text ='del', command=delete).pack()
root.mainloop()
Related
As the title suggests, I'm trying to make a counter with IntVar(),so I've tried this.
from tkinter import *
def main():
root = Tk()
root.resizable(FALSE, FALSE)
root.geometry('200x50')
root.title('Home')
#starts here
var = IntVar()
text = 'Count: ' + str(var.get())
b1 = Button(root, text='Test', command=fun)
b1.pack()
l1 = Label(root, text=text)
l1.pack()
mainloop()
def fun():
for i in range(1, 11):
print('test')
main()
But I got confused, I want to make it count the printings and show the value in the label.
Any help would be appreciated.
If you are trying to count the number of times 'test' is printed, you can update the l1 widget with l1['text'] = var after updating. To update, you can fetch the variable of intvar and then add 1 to it. Here's some code:
from tkinter import *
def main():
root = Tk()
root.resizable(FALSE, FALSE)
root.geometry('200x50')
root.title('Home')
#starts here
var = IntVar()
text = 'Count: ' + str(var.get())
b1 = Button(root, text='Test', command=lambda: fun(l1, var))
b1.pack()
l1 = Label(root, text=text)
l1.pack()
mainloop()
def fun(l1, var):
for i in range(1, 11):
print('test')
var.set(var.get()+1)
l1['text'] = 'Count: ' + str(var.get())
main()
from tkinter import ttk, simpledialog
import tkinter as tk
from tkinter import *
root = Tk()
root.resizable(0, 0)
root.title("Sorting and Searching Algorithm")
root.configure(bg='#ff8080')
root.geometry("750x550")
def arrays():
v = IntVar()
for widget in root.winfo_children():
widget.destroy()
def close():
for widget in root.winfo_children():
widget.destroy()
arrays()
titleFrame = Frame(root)
titleFrame.grid(row=0)
radioFrame = Frame(root)
radioFrame.grid(padx=350, pady=100)
inputFrame = tk.Frame(root, bg='#ff8080')
inputFrame.grid()
buttonFrame = Frame(root)
buttonFrame.grid()
Title = tk.Label(titleFrame, bg='#ff8080', text="Enter The Number of Elements In The Array", font="-weight bold")
Title.grid()
global NUMBER_OF_ENTRIES
NUMBER_OF_ENTRIES = Entry(inputFrame)
NUMBER_OF_ENTRIES.grid(row=0, column=1, sticky=E, ipadx=10, ipady=10,padx=10, pady=10)
if NUMBER_OF_ENTRIES == int:
print("Working")
else:
print("Please Enter a Integer Value")
global num
num = 0
#global NUMBER_OF_ENTRIES
#NUMBER_OF_ENTRIES = simpledialog.askinteger("Please Enter", "Enter The Number of Elements In The Array")
global alist
alist = []
for i in range (0, NUMBER_OF_ENTRIES):
num = simpledialog.askinteger("Please Enter" ,"Enter The Entries In Array Element " + str(i))
alist = alist + [ num ]
calculate = ttk.Button(buttonFrame, text="Proceed", command=entries)
calculate.grid(row=4, column=0, sticky=E + S, ipadx=10, ipady=10)
arrays()
root.mainloop()
I am trying to make it so when a user inputs a integer number into the Entry input box it stores into the variable NUMBER_OF_ENTRIES. After it stores it, it then proceeds to use the value in the further conditionals.
But I am getting an issue when I try to compile it.
Because it's not an integer. NUMBER_OF_ENTRIES is of type <class 'tkinter.Entry'>.
The usual way to do this is to associate the entry with a StringVar() which will reflect whatever is typed into the entry.
The text entered into an entry is still text so you'll have to convert it to int explicitly.
See The Tkinter Entry Widget.
I can't generate the number because I get the error NameError: name 'z' is not defined.
import tkinter as tk
from random import randint
def randomize():
z.set ( randint(x.get(),y.get()))
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root)
enterY = tk.Entry(root)
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I need help to resolve the error
You have 2 problems here.
One. You are missing z = tk.Intvar() in the global namespace.
Two. You need to assign each entry field one of the IntVar()'s.
Keep in mind that you are not validating the entry fields so if someone types anything other than a whole number you will run into an error.
Take a look at this code.
import tkinter as tk
from random import randint
def randomize():
z.set(randint(x.get(),y.get()))
print(z.get()) # added print statement to verify results.
root = tk.Tk()
x = tk.IntVar()
y = tk.IntVar()
z = tk.IntVar() # added IntVar()
text= tk.Label(root, text = "press the button for random number")
enterX = tk.Entry(root, textvariable=x) # added textvariable
enterY = tk.Entry(root, textvariable=y) # added textvariable
button = tk.Button(root, text = "Press here", command=randomize)
result = tk.Label(root,text="Number is:")
number = tk.Label(root, textvariable=z)
text.pack()
enterX.pack()
enterY.pack()
button.pack()
result.pack()
number.pack()
root.mainloop()
I have this code and basically what I want to do is I want that on pressing the button the balance at the button is updated with the amount. If the balance is currently 15, and I add 10, I want it to add 10 to it.
from tkinter import *
def bal():
ans = int (input1.get ())
total = IntVar ()
tot = int (total.get ())
tot = tot + ans
res.set(tot+ans)
root = Tk()
root.geometry("1280x720")
upper = Frame(root)
upper.pack()
Label(upper, text ="Sum:", font = ('raleway', 15), ).grid(row=0, column = 0)
Label(root, text ="Balance:", font = ('raleway', 15)).place(rely=1.0, relx=0, x=0, y=0, anchor=SW)
res = StringVar()
input1 = Entry(upper)
num2 = Entry(root)
result = Label(root, textvariable = res,font = ('raleway',13))
result.place(rely=1.0, relx=0, x=80, y=-2, anchor=SW)
input1.grid(row=0,column=2)
Button(upper, text ="Add Funds", command = bal).grid(row=4, column=2, ipadx = 65)
mainloop()
root.mainloop()
I tried to have a total that constantly updates in the function bal but it doesn't update for some reason. I am a python beginner, by the way :D
Thanks for your help!
In the bal() command function, all you need to do is retrieve the current input value and running total (balance), add them together, and then update the running total:
from tkinter import *
def bal():
ans = input1.get()
ans = int(ans) if ans else 0
tot = int(res.get())
tot = tot + ans
res.set(tot)
root = Tk()
root.geometry("1280x720")
upper = Frame(root)
upper.pack()
Label(upper, text="Sum:", font=('raleway', 15)).grid(row=0, column=0)
Label(root, text="Balance:", font=('raleway', 15)).place(rely=1.0, relx=0,
x=0, y=0, anchor=SW)
res = StringVar()
res.set(0) # initialize to zero
input1 = Entry(upper)
result = Label(root, textvariable=res, font=('raleway', 13))
result.place(rely=1.0, relx=0, x=80, y=-2, anchor=SW)
input1.grid(row=0,column=2)
Button(upper, text="Add Funds", command=bal).grid(row=4, column=2, ipadx=65)
root.mainloop()
You created a new IntVar and you are using .get on this. Instead you want to be use get on num2 to get the current number that is stored in there adding the input to this and updating the var.
from tkinter import *
root = Tk()
root.title("Tip & Bill Calculator")
totaltxt = Label(root, text="Total", font=("Helvitca", 16))
tiptxt = Label(root, text="Tip (%)", font=("Helvitca", 16))
peopletxt = Label(root, text="people", font=("Helvitca", 16))
totaltxt.grid(row=0, sticky=E)
tiptxt.grid(row=1, sticky=E)
peopletxt.grid(row=2, sticky=E)
totalentry = Entry(root)
tipentry = Entry(root)
peopleentry = Entry(root)
totalentry.grid(row=0, column=2)
tipentry.grid(row=1, column=2)
peopleentry.grid(row=2, column=2)
ans = Label(root, text = "ANS")
ans.grid(row=4)
def answer(event):
data1 = totalentry.get()
data2 = tipentry.get()
data3 = peopleentry.get()
if tipentry.get() == 0:
ans.configure(str((data1/data3)), text="per person")
return
elif data1 == 0:
ans.configure(text="Specify the total")
return
elif data3 == 0 or data3 ==1:
ans.configure(str(data1*(data2/100+1)))
return
elif data1 == 0 and data2 == 0 and data3 ==0:
ans.configure(text = "Specify the values")
return
else:
ans.configure(str((data1*(data2/100+1)/data3)), text="per person")
return
bf = Frame(root)
bf.grid(row=3, columnspan=3)
calc = Button(bf, text ="Calculate", fg = "black", command = answer)
calc.bind("<Button-1>", answer)
calc.grid(row=3, column=2)
root.mainloop()
I'm trying to make a tip and bill calculator with a simple design just to learn and experiment. However, I encountered a horrible problem that kept haunting for days, I usually struggle with functions in python and I'm trying to bind a function to a calculate button, which I managed to make it appear. However, I can't manage to get it to work. After some messing around I ended with this error, when I click the calculate button.
This is the error after I click the calculate button:
TypeError: answer() missing 1 required positional argument: 'event'
Commands bound to a button do not get an argument, as the nature of the event is already known. Delete 'event'.
You also bind the answer function to an event. The result is that answer is called both without and with an event argument. Get rid of the bind call.
Follow hint given by Bryan. Stop passing a digit string to .configure as a positional parameter. tk will try to interpret is as dictionary. Instead, add the number string to the rest of the label string.
Like rows, columns start from 0.
The frame is not needed.
The following revision works.
from tkinter import *
root = Tk()
root.title("Tip & Bill Calculator")
totaltxt = Label(root, text="Total", font=("Helvitca", 16))
tiptxt = Label(root, text="Tip (%)", font=("Helvitca", 16))
peopletxt = Label(root, text="people", font=("Helvitca", 16))
totaltxt.grid(row=0, column=0, sticky=E)
tiptxt.grid(row=1, column=0, sticky=E)
peopletxt.grid(row=2, column=0, sticky=E)
totalentry = Entry(root)
tipentry = Entry(root)
peopleentry = Entry(root)
totalentry.grid(row=0, column=1)
tipentry.grid(row=1, column=1)
peopleentry.grid(row=2, column=1)
ans = Label(root, text = "ANS")
ans.grid(row=4, column=0, columnspan=2, sticky=W)
def answer():
total = totalentry.get()
tip = tipentry.get()
people = peopleentry.get()
if not (total and tip):
ans['text'] = 'Enter total and tip as non-0 numbers'
else:
total = float(total)
tip = float(tip) / 100
people = int(people) if people else 1
ans['text'] = str(round(total * tip / people, 2)) + " per person"
calc = Button(root, text ="Calculate", fg = "black", command = answer)
calc.grid(row=3, column=1)
root.mainloop()