I am making a small project currency converter. When I convert USD to any other currency, it correctly displays the correct answer. If I choose another currency except for USD, the result comes as the same digit/amount as I put. But I want to convert entered currency into to_currency. How can I fix it?
# Import the modules needed
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
import requests
url = 'https://v6.exchangerate-api.com/v6/8a0fcd7df32ea4704f4fc48d/latest/USD'
response = requests.get(url)
response.raise_for_status()
data = response.json()
currency_key = data['conversion_rates']
def convert():
input_02.delete(0, END)
amount = input_01.get()
if amount == "":
messagebox.showinfo(title="Invalid", message="Please Insert the Amount")
return False
currency_02 = to_currency.get()
for i, j in currency_key.items():
var01 = i.upper()
var02 = currency_02.upper()
if var01 in var02:
try:
if from_currency.get() != 'USD':
amount = float(amount)/j
value = amount*j
input_02.insert(0, f"{value}")
else:
value = j*float(amount)
value = round(value, 4)
input_02.insert(0, f"{value}")
except ValueError:
messagebox.showinfo(title="Invalid", message="Please insert Amount in Digits")
window = Tk()
window.title('Currency Converter!')
window.iconbitmap('currency.ico')
window.config(padx=50, bg='#0CA7D3')
label_01 = Label(text="Currency Converter GUI", bg='#0CA7D3', foreground='white', font=("arial", 20, "bold"))
label_01.grid(column=0, row=0, columnspan=3, pady=15)
from_currency = StringVar()
from_currency.set(" USD ")
dropdown_01 = ttk.Combobox(textvariable=from_currency, width=16, font=("arial", 10, "bold"), state='enable',
values=list(currency_key))
dropdown_01.grid(column=0, row=1)
input_01 = Entry(font=("arial", 10, "bold"), width=19)
input_01.focus()
input_01.grid(column=0, row=2, pady=5)
to_currency = StringVar()
to_currency.set(" PKR ")
dropdown_02 = ttk.Combobox(textvariable=to_currency, width=16, font=("arial", 10, "bold"), state='readonly',
values=list(currency_key))
dropdown_02.grid(column=2, row=1)
input_02 = Entry(font=("arial", 10, "bold"), width=19)
input_02.grid(column=2, row=2, pady=5)
button = Button(text="Convert", command=convert, width=8, bg='#0084AB', fg='white', font=("arial", 10, "bold"))
button.grid(column=0, row=3, pady=20)
window.mainloop()
The rate for from_currency to to_currency can be calculated by:
rate = currency_key[to_currency.get()] / currency_key[from_currency.get()]
Below is the modified convert():
def convert():
amount = input_01.get().strip()
if amount == "":
messagebox.showinfo(title="Invalid", message="Please insert the amount")
return False
try:
rate = currency_key[to_currency.get()] / currency_key[from_currency.get()]
value = float(amount) * rate
input_02.delete(0, "end")
input_02.insert("end", value)
except ValueError:
messagebox.showinfo(title="Invalid", message="Please insert amount in digits")
I have not tried to run the code, but looking at this:
amount = float(amount)/j
value = amount*j
input_02.insert(0, f"{value}")
You are multiplying and dividing amount by j, so the final value is equal to the initial amount.
As a side note, I would try to use variable names which are a little bit more descriptive.
Related
In my code, I have tried to get the user input through text fields, store them in variables and finally print them in a tabular form.
The problem I am facing is that none of the values I enter through the text fields get displayed; when I try printing the variables, they come up empty.
Here's part of my code:
# SPASC
from tkinter import *
import tkinter as tk
import tkinter.ttk as tktrv
root = tk.Tk()
root.title("SPASC")
root.geometry("410x400")
lb1 = Label(root, text="SPASC \n Welcomes You !!!", fg="red", bg="sky blue"
, font=('Arial Black', 20), width=22, anchor=CENTER)
lb2 = Label(root, text="What would you like to compare?",
font=('Arial', 18), anchor=CENTER)
space1 = Label(root, text="\n\n")
lb1.grid(row=0)
lb2.grid(row=5)
space1.grid(row=1)
hpw, mil = StringVar(), StringVar()
def bt_cars():
w1 = Toplevel()
w1.title("Choose Features")
w1.geometry("430x200")
lb3 = Label(w1, text="Choose features for comparison", bg="yellow"
, font=('Arial Black', 18), width=25)
lb4 = Label(w1, text=" ", anchor=CENTER)
fr1 = LabelFrame(w1, width=20, padx=100)
hpw_cb = Checkbutton(fr1, text="Horsepower", variable=hpw, anchor='w', onvalue="Horsepower", offvalue="")
hpw_cb.grid()
hpw_cb.deselect()
mil_cb = Checkbutton(fr1, text="Mileage", variable=mil, anchor='w', onvalue="Mileage", offvalue="")
mil_cb.grid()
mil_cb.deselect()
var_stor = [hpw, mil]
print(hpw)
print(mil)
var_fill = []
for itr1 in var_stor:
if itr1 != "":
var_fill.append(itr1)
print(var_fill)
def car_1():
name1 = StringVar()
c1 = Toplevel()
c1.title("Car 1")
c1.geometry("430x200")
car1_lb1 = Label(c1, text="Car Name:")
name1_ifl = Entry(c1)
name1 = name1_ifl.get()
elm_var_fill = len(var_fill)
ct1 = 0
car1_val = []
for itr2 in var_fill:
if ct1 == elm_var_fill:
break
lb5 = Label(c1, text=itr2.get())
#Creating text field
ftr1_ifl = Entry(c1)
car1_ftr = ftr1_ifl.get()
car1_val.append(car1_ftr)
car1_ftr = None
lb5.grid(row=ct1 + 2, column=1)
ftr1_ifl.grid(row=ct1 + 2, column=2)
ct1 += 1
print(car1_val)
def display():
dp = Toplevel()
dp.title("Results")
dp.geometry("500x200")
car1_pt = 0
car2_pt = 0
car_tree = tktrv.Treeview(dp)
car_tree["columns"] = ("car1col")
car_tree.column("#0", width=120, minwidth=30)
car_tree.column("car1col", width=120, minwidth=30)
car_tree.heading("#0", text="Features" )
car_tree.heading("car1col", text=str(name1))
car_tree.pack()
c1.withdraw()
print(var_fill)
done1_bt = Button(c1, text="Continue", command=display)
name1_ifl.grid(row=0, column=2)
car1_lb1.grid(row=0, column=1)
done1_bt.grid(row=5,column=1)
w1.withdraw()
done_bt = Button(w1, text="Done", command=car_1)
done_bt.grid(row=3, column=1)
lb3.grid(row=0, column=1)
lb4.grid(row=1, column=1)
fr1.grid(row=2, column=1)
root.withdraw()
bt1 = Button(root, text="CARS", width=5, font=('Calibri', 15), command=bt_cars)
bt1.grid(row=7)
space2 = Label(root, text="\n\n")
space2.grid(row=6)
root.mainloop()
I am facing trouble with the variables named: hpw, mil, name1.
Any help would be welcome.
NOTE:- Please excuse the amount of code; I wanted others to replicate the error and see it for themselves
For the variables hpw and mil, these variables are empty strings that's why you are not getting any value from those checkboxes. To get values from the checkboxes replace these lines of code:
var_stor = [hpw, mil]
with
var_stor = [hpw_cb.cget('onvalue'), mil_cb.cget('onvalue')]
since you want the onvalue then you must use cget() method to access those values.
also, replace
lb5 = Label(c1, text=itr2.get())
with
lb5 = Label(c1, text=itr2)
because now you have required values (not objects) in a list, so just need to access those values.
For the variable name1 you can use #BokiX's method.
The problem is you are using get() wrong. You cannot use get() right after Entry() because as soon as entry is created it's getting the input before the user can even input something.
Use this code:
def get_input(text):
print(text)
e = Entry(root)
e.pack()
b = Button(root, text="Print input", command=lambda: get_input(e.get()))
b.pack()
Now get() method will not be executed before you click the button.
I work on a program that calculates the macros of each meal. You can enter a value in gram and it calculates for each aliment your intake. I would like now to add these values together when I push multiple buttons. Then I'll display the value somewhere and maybe I could do a graph after.
Here I show what my program looks like :
import tkinter as tk
def value_kiwi():
value = ent_quantity.get()
formula = (float(value)/100)
cal = 53
pro = 1.6
glu = 11.1
li = 0.3
Calories = (cal) * formula
Protéines = (pro) * formula
Glucides = (glu) * formula
Lipides = (li) * formula
lbl_cal["text"] =f"{Calories}"
lbl_prot["text"] = f"{Protéines}"
lbl_glu["text"] = f"{Glucides}"
lbl_lip["text"] = f"{Lipides}"
def value_banane():
value = ent_quantity.get()
formula = (float(value)/100)
cal = 90
pro = 1.5
glu = 20.1
li = 0
Calories = (cal) * formula
Protéines = (pro) * formula
Glucides = (glu) * formula
Lipides = (li) * formula
lbl_cal["text"] =f"{Calories}"
lbl_prot["text"] = f"{Protéines}"
lbl_glu["text"] = f"{Glucides}"
lbl_lip["text"] = f"{Lipides}"
window = tk.Tk()
window.title("Calculateur de Calories et Nutriments")
frm_entry = tk.Frame(master=window)
ent_quantity = tk.Entry(master=frm_entry, width=5)
ent_quantity.grid(row=1, column=0,)
lbl_cal = tk.Label(master=window)
lbl_cal.grid(row=1, column=1,)
lbl_prot = tk.Label(master=window)
lbl_prot.grid(row=1, column=2)
lbl_glu = tk.Label(master=window)
lbl_glu.grid(row=1, column=3)
lbl_lip = tk.Label(master=window)
lbl_lip.grid(row=1, column=4)
btn_kiwi = tk.Button(
master=window,
text="Kiwi",
command=value_kiwi,
)
btn_banane = tk.Button(
master=window,
text="Banane",
command=value_banane,
)
lbl_calories = tk.Label(master=window, text="Calories",)
lbl_proteines = tk.Label(master=window, text="Protéines")
lbl_glucides = tk.Label(master=window, text="Glucides")
lbl_lipides = tk.Label(master=window, text="Lipides")
lbl_fruits = tk.Label(master=window, text="Fruits")
frm_entry.grid(row=1, column=0, padx=10)
lbl_calories.grid(row=0,column=1, padx=5, sticky="w")
lbl_proteines.grid(row=0, column=2, padx=10)
lbl_glucides.grid(row=0, column=3, padx=10)
lbl_lipides.grid(row=0,column =4, padx=10)
lbl_fruits.grid(row=1,column =5, padx=10)
btn_kiwi.grid(row=2, column=5, pady=10)
btn_banane.grid(row=3, column=5, pady=10)
window.mainloop()
Ok, I think I improved Your code:
from tkinter import Tk, Button, Entry, Label
class MainWindow(Tk):
def __init__(self):
Tk.__init__(self)
self.title('Nutrient calculator')
# entry
Label(self, text='Amount').grid(row=0, column=0)
self.amount = Entry(self, width=5, bg='light grey')
self.amount.grid(row=1, column=0)
# calories
Label(self, text='Calories').grid(row=0, column=1)
self.calories = Label(self)
self.calories.grid(row=1, column=1)
# proteins
Label(self, text='Proteins').grid(row=0, column=2)
self.proteins = Label(self)
self.proteins.grid(row=1, column=2)
# glucose
Label(self, text='Glucose').grid(row=0, column=3)
self.glucose = Label(self)
self.glucose.grid(row=1, column=3)
# lipids
Label(self, text='Lipids').grid(row=0, column=4)
self.lipids = Label(self)
self.lipids.grid(row=1, column=4)
# list of all labels
self.data_labels = [self.calories, self.proteins, self.glucose, self.lipids]
# error label for if no value is entered or it cannot be converted
self.error_label = Label(self, text='Use integer or float value!')
# stuff for adding multiple foods
self.do_add = False
self.nutrient_list = []
self.plus_btn = Button(self, text='Add', command=self.add)
self.plus_btn.grid(row=3, column=0, columnspan=4, sticky='nwes')
def display_values(self, value_list):
self.nutrient_list.append(value_list)
if len(self.nutrient_list) == 2 and not self.do_add:
self.nutrient_list.pop(0)
elif len(self.nutrient_list) > 2 and not self.do_add:
self.nutrient_list = [self.nutrient_list[-1]]
print(self.nutrient_list)
if self.do_add:
value_list = []
for i in range(len(self.nutrient_list[0])):
total_value = 0
for item in self.nutrient_list:
total_value += item[i]
value_list.append(total_value)
for text, label in zip(value_list, self.data_labels):
label.config(text=f'{text:.2f}')
self.do_add = False
def handle_value_error(self):
self.error_label.grid(row=2, column=0, columnspan=4)
def add(self):
self.do_add = True
self.amount.delete(0, 'end')
class Values:
def __init__(self, name, row, column, calories, proteins, glucose, lipids):
self.parent = root
self.name = name
self.row = row
self.column = column
self.calories = calories
self.proteins = proteins
self.glucose = glucose
self.lipids = lipids
self.stuff_list = [self.calories, self.proteins, self.glucose, self.lipids]
self.button = Button(self.parent, text=self.name, command=self.set_values)
self.button.grid(row=self.row, column=self.column, sticky='nwse')
def set_values(self):
value_list = []
value_ = self.parent.amount.get()
try:
formula = float(value_) / 100
self.parent.error_label.grid_forget()
for item in self.stuff_list:
item *= formula
value_list.append(item)
self.parent.display_values(value_list)
except ValueError:
self.parent.handle_value_error()
root = MainWindow()
kiwi = Values('Kiwi', 2, 4, calories=53, proteins=1.6, glucose=11.1, lipids=0.3)
banana = Values('Banana', 3, 4, calories=90, proteins=1.5, glucose=20.1, lipids=0)
root.mainloop()
it is not necessarily better however a few benefits from using this code are:
better organization (IMO) since it uses classes which make it pretty neat (however You have to have an understanding over them)
takes less space - what I mean is that now, to define a new food, You just have to initiate the Values class and give it the necessary arguments. You can take an example from the given instances.
possibly easier to expand (both because better organization and takes less space)
I edited the code so now it should have that functionality, the way it works is You choose an amount , then fruit and if You want to add more, press add button, then choose amount, press food and it will display the total so far, then again, if You want to add more press add and then put in an amount and press the fruit, currently the way to 'clear' is to press any food button and it should then reset the whole list and keep only the one that was just pressed and then repeat.
tkinter/python newbie here. I built a calculator using tkinter and I can't seem to find any way to allow python to detect alphabetical characters entered into the entry widget. My goal is to let it detect the alphabetical characters and display an error message.
Heres my code:
from tkinter import *
root = Tk()
#Title of the Window(s)
root.title("Jeff's Geometry Calculator")
#Fonts for this project
LARGEFONT = ("Verdana", 35)
BUTTONFONT = ("Times", 15)
ANSWERFONT = ("Courier", 25, "bold")
ANSWERLABELFONT = ("Courier", 25)
DESCRIPTIONFONT = ("Verdana", 18)
DESCRIPTIONFONT1 = ("Verdana", 12)
descriptionLabel = Label(root, text="Cube Volume Calculator", font=LARGEFONT, padx=50, pady=50)
descriptionLabel.grid(row=0, column=0)
equationLabel = Label(root, text="Cube Volume Equation: l³", font=DESCRIPTIONFONT)
equationLabel.grid(row=1, column=0)
equationLabel1 = Label(root, text="Note: l = length", font=DESCRIPTIONFONT1)
equationLabel1.grid(row=2, column=0)
numEntry = Entry(root, width=10)
numEntry.grid(row=3, column=0)
def cubeVolumeAnswer():
cubeNum = (numEntry.get())
result = float(cubeNum) * float(cubeNum) * float(cubeNum)
answerLabel.config(text=str(result))
myButton = Button(root, text="Calculate", font=BUTTONFONT, command=cubeVolumeAnswer, padx=50, pady=50)
myButton.grid(row=4, column=0)
number = str(numEntry.get())
answerLabel = Label(root, text="", font=ANSWERFONT)
answerLabel.grid(row=6, column=0)
answerLabel1 = Label(root, text="Answer: ", font=ANSWERLABELFONT)
answerLabel1.grid(row=5, column=0)
root.mainloop()
Thanks in advance!
You can use a try/except statement, basically, try will attempt to preform the task but in case of error, instead of an intimidating error message in the console, it will execute the except block:
try:
print(1 + z)
except:
print("invalid equation")
in your case you can simply:
def cubeVolumeAnswer():
cubeNum = (numEntry.get())
try:
result = float(cubeNum) * float(cubeNum) * float(cubeNum)
except:
result = "invalid equation"
answerLabel.config(text=str(result))
I'm trying to write calculator code which contains only plus mode and minus mode and BMI calculator. I've tried everything I know so far but I can't figure it out that why my code is unable to use
Here is my Bmi code:
from tkinter import *
def bmi():
kg = int(box1.get())
m = int(box2.get())
result =(kg)/(m^2)
result.configure(result).grid(row=2,column=1)
return
root = Tk()
root.option_add("*font", "impact 16")
Label(root, text= "wight(kg.)").grid(row=0,column=0)
box1 = Entry(root).grid(row=0,column=1)
Label(root, text= "hight(m.)").grid(row=1,column=0)
box2 = Entry(root).grid(row=1,column=1)
Label(root, text= "BMI",command=bmi).grid(row=2,column=0)
Button(root, text= "calculate").grid(row=3,columnspan=2)
root.mainloop()
and there is my calculator code
import tkinter as tk
def show_output():
number = int(number1_input.get())
if number == 1:
output_label.configure(text="plus")
number0_ask = tk.Label(master=window, text='input first number')
number0_input = tk.Entry(master=window,width= 15)
number2_ask = tk.Label(master=window, text='input second number')
number2_input = tk.Entry(master=window, width=15)
sum = int(number0_input)+int(number2_input)
output_label2.configure(sum)
elif number == 2:
output_label.configure(text="plus")
number0_ask = tk.Label(master=window, text='input first number')
number0_input = tk.Entry(master=window, width=15)
number2_ask = tk.Label(master=window, text='input second number')
number2_input = tk.Entry(master=window, width=15)
sum = int(number0_input) + int(number2_input)
output_label2.configure(sum)
else:
output_label2.configure("none of our program")
return
window = tk.Tk()
window.title("calulator")
window.minsize(width=400, height=400)
tittle_label = tk.Label(master=window, text="enter order 1 for plus 2 for minus")
tittle_label.pack(pady=20)
number1_input = tk.Entry(master=window, width=15)
number1_input.pack(pady=20)
go_button = tk.Button(master=window, text="result", command=show_output, width=15,
height=2)
go_button.pack(pady=20)
output_label = tk.Label(master=window)
output_label.pack(pady=20)
output_label2 = tk.Label(master=window)
output_label2.pack(pady=20)
window.mainloop()
I am a beginner. I have tried everything to make the following code take numeric inputs into entry boxes and do a calculation with them. I am getting the ValueError and nothing I do makes that stop happening. This is supposed to be a program that calculates monthly interest payments and a total paid out. I am keeping it at a simple product until I fix this much more basic problem. Thanks.
def multiply(var1, var2, var3):
product = float(var1 * var2 * var3)
return product
def btnClick(event):
x = float(entry.get())
main = Tk()
main.title("Assignment 16")
main.geometry("500x500")
main["bg"] = "#000066"
lblFirst = Label(main, text="Amount to Pay: ")
lblFirst.grid(row=0, column=3, pady=5)
entry = Entry(main, width=20)
entry.grid(row=0, column=4)
amount = entry.get()
lblSecond = Label(main, text="Interest Rate (like 7.5): ")
lblSecond.grid(row=2, column=3, pady=10)
entry2 = Entry(main, width=20)
entry2.grid(row=2, column=4)
rate = entry2.get()
lblThird = Label(main, text="Years to Pay: ")
lblThird.grid(row=4, column=3, pady=15)
entry3 = Entry(main, width=20)
entry3.grid(row=4, column=4)
years = entry3.get()
try:
# Try to make it a float
if amount.isnumeric():
amount = float(amount)
except ValueError:
# Print this if the input cannot be made a float
print("Bad input")
try:
# Try to make it a float
if rate.isnumeric():
rate = float(rate)
except ValueError:
# Print this if the input cannot be made a float
print("Bad input")
try:
# Try to make it a float
if years.isnumeric():
years = int(years)
except ValueError:
# Print this if the input cannot be made a float
print("Bad input")
lblFourth = Label(main, text="Monthly Payment: ")
lblFourth.grid(row=6, column=3, pady=15)
lblFourthTwo = Label(main, text="XXXXX")
lblFourthTwo.grid(row=6, column=4)
lblFifth = Label(main, text="Total of Paymenta: ")
lblFifth.grid(row=8, column=3, pady=15)
lblFifthTwo = Label(main, text="XXXXX")
lblFifthTwo.grid(row=8, column=4)
button1 = Button(main, text='Convert', width=10, command=btnClick)
button2 = Button(main, text='Calculate', width=10, command=multiply(amount, rate, years))
button1.grid(padx=20, pady=20)
main.mainloop()
All your code runs before the mainloop starts.
Programs using GUI-toolkits like tkinker are event-driven. Your code only runs in the set-up before the mainloop and after that in event-handlers.
You can use validation to ensure that only numbers are entered.
Working example (for Python 3) below. This also shows how to get the value from an editbox in an event handler and how to create synthetic events to update other widgets.
import tkinter as tk
from tkinter import ttk
# Creating and placing the widgets
root = tk.Tk()
root.wm_title('floating point entry')
qedit = ttk.Entry(root, justify='right')
qedit.insert(0, '100')
qedit.grid(row=0, column=0, sticky='ew')
result = ttk.Label(root, text='100')
result.grid(row=1, column=0)
ttk.Button(root, text="Exit", command=root.quit).grid(row=2, column=0)
# Callback functions
def is_number(data):
if data == '':
return True
try:
float(data)
print('value:', data)
except ValueError:
return False
result.event_generate('<<UpdateNeeded>>', when='tail')
return True
def do_update(event):
w = event.widget
number = float(qedit.get())
w['text'] = '{}'.format(number)
# The following settings can only be done after both the
# widgets and callbacks have been created.
vcmd = root.register(is_number)
qedit['validate'] = 'key'
qedit['validatecommand'] = (vcmd, '%P')
result.bind('<<UpdateNeeded>>', do_update)
# Run the event loop.
root.mainloop()