ValueError: could not convert string to float: in tkinter - python

I could not convert the entry widget values into float for the calculation inside function.
from tkinter import *
def bac_calc():
#gender_condition
gend=gender.get()
if gend == "Male":
k1=0.015
k2=0.080
elif gend == "Female":
k1=0.020
k2=0.075
#weight
kg=body_weight.get()
kg=float(kg)
wt_lbs=kg*2.20462
bac=k1*k2*wt_lbs*100
t= "weight in pound is " , float(bac)
Label(master, text=t).grid(row=23, column=1)
master = Tk()
master.title('Blood Alcohol Level calculator')
#Gender
gender=StringVar()
Label(master, text="Select your gender").grid(row=2, column=0, sticky=W, pady=5)
r1=Radiobutton(master, text="Male", padx=20, variable=gender, value="Male", command=bac_calc).grid(row=3, column=2, sticky=W, pady=5)#anchor
r2=Radiobutton(master, text="Female", padx=20, variable=gender, value="Female", command=bac_calc).grid(row=3, column=3, sticky=W, pady=5)
#Body weight
Label(master, text="Enter the body weight kg").grid(row=5, column=0, sticky=W, pady=5)
body_weight=Entry(master)
body_weight.grid(row=6, column=2)
#Evaluate and Quit
Button(master, text="Evaluate", command=bac_calc).grid(row=8, column=2, sticky=W, pady=5)
Button(master, text="Quit ", command=master.quit).grid(row=9, column=4, sticky=W, pady=5)
master.mainloop()
Can you help me with the problem?
Thanks in advance!!
Sorry for a long code. Anyways,the there are only input widgets and calculations.

As suggested by #PM 2Ring, you should consider adding a default value to the Entry element represented by body_weight. You can use the insert method to do this after creating body_weight.
See here.

Ive cleaned up your code a little bit and I've added an error handling statement for your float conversion problem. One thing you might consider doing is finding the formula for BAC calculations that utilizes kilograms instead of converting it to pounds. Also I would recommend looking up the PEP8 style guides. It helps keep code readable. Hope this helps :)
from tkinter import *
def bac_calc():
# gender_condition
gend = gender.get()
if gend == "Male":
k1 = 0.015
k2 = 0.080
else:
k1 = 0.020
k2 = 0.075
# weight
try:
kg = body_weight.get()
kg = float(kg)
wt_lbs = kg * 2.20462
bac = k1 * k2 * wt_lbs * 100
t = "weight in pound is ", float(bac)
Label(master, text=t).grid(row=23, column=1)
except ValueError as e:
Label(master, text='Input must be numerical.').grid(row=23, column=1)
master = Tk()
master.title('Blood Alcohol Level calculator')
# Gender
gender = StringVar()
Label(master, text="Select your gender").grid(row=2, column=0, sticky=W, pady=5)
r1 = Radiobutton(master, text="Male", padx=20, variable=gender, value="Male", command=bac_calc).grid(row=3, column=2,
sticky=W,
pady=5) # anchor
r2 = Radiobutton(master, text="Female", padx=20, variable=gender, value="Female", command=bac_calc).grid(row=3,
column=3,
sticky=W,
pady=5)
# Body weight
Label(master, text="Enter the body weight kg").grid(row=5, column=0, sticky=W, pady=5)
body_weight = Entry(master)
body_weight.grid(row=6, column=2)
# Evaluate and Quit
Button(master, text="Evaluate", command=bac_calc).grid(row=8, column=2, sticky=W, pady=5)
Button(master, text="Quit ", command=master.quit).grid(row=9, column=4, sticky=W, pady=5)
master.mainloop()

Related

RadioButton not selected tkinter

I've been learning tkinter and I ran into this thing I don't understand, what does it mean when a radio button has a '-'? it's like is neither marked nor unmarked, is it not returning anything?
I grabbed this code from the internet so anyone can see what I mean:
from tkinter import *
root = Tk()
btn1 = StringVar()
def do_something():
val0 = entry1.get()
val1 = btn1.get()
print("The variable values are " + val1 + " and " + val0)
print("The method values are " + btn1.get() + " and " + entry1.get())
rb1 = Radiobutton(root, text="Euro", value="euro",
variable=btn1).grid(row=2, column=1, sticky=W)
rb2 = Radiobutton(root, text="Dollar", value="dollar",
variable=btn1).grid(row=3, column=1, sticky=W)
rb3 = Radiobutton(root, text="Yen", value="yen",
variable=btn1).grid(row=4, column=1, sticky=W)
label1 = Label(root, text="Input Here")
label1.grid(row=1, sticky=E)
entry1 = Entry(root)
entry1.grid(row=1, column=1, sticky=W)
go = Button(root, text="Print Selection", fg="white",
bg="black", command=do_something)
go.grid(row=10, columnspan=3)
root.mainloop()
This happened to me in a class as well, a group of radio buttons have this hyphen in them until I bound self to the StringVar(), what's happening under the hood?
Use IntVar() instead of StringVar(). In Python 3.8+ Used f-string format.
Here is code:
from tkinter import *
root = Tk()
btn1 = IntVar()
def do_something():
val0 = float(entry1.get())
val1 = val0
print(f"The variable values are {val1} and {val0}")
print(f"The method values are {val1} and {val0}")
rb1 = Radiobutton(root, text="Euro", value="euro",
variable=btn1).grid(row=2, column=1, sticky=W)
rb2 = Radiobutton(root, text="Dollar", value="dollar",
variable=btn1).grid(row=3, column=1, sticky=W)
rb3 = Radiobutton(root, text="Yen", value="yen",
variable=btn1).grid(row=4, column=1, sticky=W)
label1 = Label(root, text="Input Here")
label1.grid(row=1, sticky=E)
entry1 = Entry(root)
entry1.grid(row=1, column=1, sticky=W)
go = Button(root, text="Print Selection", fg="white",
bg="black", command=do_something)
go.grid(row=10, columnspan=3)
root.mainloop()
Result before:
Result after:

Where can I edit the Copyright of my Python Bundle created with py2app?

I use py2app for the creation of stand alone apps from my python scripts. I have Tkinter used in the script called "MyApp" but I wonder where I can edit the copyright of my app? When I go to "About MyApp" from menu bar which was created by py2app, I see the Tkinter copyright.
So, what do I need to do to get my own name for my own app in py2app here?
Wishes,
Mike
from tkinter import *
from tkinter import messagebox
root = Tk()
root.wm_title("Calculate something")
root.config(background="#FFFFFF")
leftFrame = Frame(root, width=200, height=400)
leftFrame.grid(row=0, column=0, padx=10, pady=3)
leftLabel1 = Label(leftFrame, text="This app helps to calculate")
leftLabel1.grid(row=0, column=0, padx=10, pady=3)
rightFrame = Frame(root, width=200, height=400)
rightFrame.grid(row=0, column=1, padx=10, pady=3)
rightLabel1 = Label(rightFrame, text="1st number:")
rightLabel1.grid(row=0, column=1, padx=10, pady=3)
rightLabel2 = Label(rightFrame, text="2nd number")
rightLabel2.grid(row=1, column=1, padx=10, pady=3)
rightLabel3 = Label(rightFrame, text="you get")
rightLabel3.grid(row=3, column=1, padx=10, pady=25)
num1_var = DoubleVar()
num2_var = DoubleVar()
# entrys
num1_ent = Entry(rightFrame, width=30, textvariable=num1_var)
num1_ent.grid(row=0, column=2, padx=10, pady=3)
num2_ent = Entry(rightFrame, width=30, textvariable=num2_var)
num2_ent.grid(row=1, column=2, padx=10, pady=3)
def calc():
num1 = num1_var.get()
num2 = num2_var.get()
if num1 == num2:
messagebox.showerror(titel = "Error", message = "Different numbers are needed", icon = "error")
elif num1 < num2:
rightLabel4 = Label(rightFrame, width=30, text=((num2 - num1)-1))
rightLabel4.grid(row=3, column=2, padx=10, pady=25)
elif num1 > num2:
rightLabel4 = Label(rightFrame, width=30, text=((num2 - num1)-5))
rightLabel4.grid(row=3, column=2, padx=10, pady=25)
buttonFrame = Frame(rightFrame)
buttonFrame.grid(row=3, column=1, padx=10, pady=3)
B1 = Button(rightFrame, text="Do it", bg="#FF0000", width=15, command=calc)
B1.grid(row=2, column=2, padx=50, pady=10)
root.mainloop()

im using .get() to return the value of the entry box named 'fName' and then print it on the click of the button... but its not working

from tkinter import *
root = Tk()
fN = StringVar()
sN = StringVar()
age = StringVar()
yG = StringVar()
Label(root, text="First Name").grid(row=0, sticky=W, padx=4)
fName = Entry(root, width=50, textvariable=fN ).grid(row=0, column=1, sticky=E, pady=4)
Label(root, text="Surname").grid(row=1, sticky=W, padx=4)
sName = Entry(root, width=50, textvariable=sN).grid(row=1, column=1, sticky=E, pady=4)
Label(root, text="Age").grid(row=2, sticky=W, padx=4)
age = Entry(root, width=50, textvariable=age).grid(row=2, column=1, sticky=E, pady=4)
Label(root, text="Year Group").grid(row=3, sticky=W, padx=4)
yearGruop = Entry(root, width=50, textvariable=yG).grid(row=3, column=1, sticky=E, pady=4)
fName_1 = fN.get()
returning the value of the StringVar 'fN' and storing it
def print_():
print (fName_1)
not printing the contents of the first name entry box ##
Button(root, text="Create account", command=print_).grid(row=4, column=1)
root.mainloop()
Right now you are getting the contents as soon as you started the program thus you are getting empty value.
You need to get the value after clicking the button which means you should put the code that gets value inside of your method.
def print_():
fName_1 = fN.get()
print (fName_1)
Also, in your code fName, sName etc. are all set to None since grid() returns None. If you want to use them later you need to use grid on separate line.
fName = Entry(root, width=50, textvariable=fN )
fName.grid(row=0, column=1, sticky=E, pady=4)
Another point is, you don't need those stringvar values in your code either. You can directly get contents of Entry using get.
fName = Entry(root, width=50, textvariable=fN )
fName.grid(row=0, column=1, sticky=E, pady=4)
def print_():
print (fName.get())

How to print values into a Label in Tkinter

I want to write a small app that counts net amount and tax. I wrote this code and I've tried many times using var.set() based on this post but I have no idea how do it correctly.
from tkinter import *
import tkinter as tk
def count23():
b = gross.get()
n = round(b/1.23, 2)
v = round(b - n, 2)
# print here works, but prints in shell
def count8():
b = gross.get()
n = round(b/1.08, 2)
v = round(b - n, 2)
def count5():
b = gross.get()
n = round(b/1.05, 2)
v = round(b - n, 2)
root = tk.Tk()
gross = DoubleVar()
root.geometry('220x200+250+250')
L1 = Label(root, text='Input gross ammount').grid(row=0, column=0, columnspan=5)
E1 = Entry(root, textvariable=gross).grid(row=1, column=1, columnspan=3, sticky='WE', padx=5, pady=5)
L2 = Label(root, text='Choose your tax rate').grid(row=2, column=0, columnspan=5)
B1 = Button(root, text='5 %', command=count5)
B1.grid(row=3, column=0, padx=5, pady=5)
B2 = Button(root, text='8 %', command=count8)
B2.grid(row=3, column=2, padx=5, pady=5)
B3 = Button(root, text='23 %', command=count23)
B3.grid(row=3, column=4, padx=5, pady=5)
L3 = Label(root, text=' ').grid(row=4, column=0, columnspan=5)
L4 = Label(root, text='Net').grid(row=5, column=0, columnspan=2, sticky='WE')
L5 = Label(root, text='TAX').grid(row=5, column=3, columnspan=2, sticky='WE')
L6 = Label(root, relief='raised')
L6.grid(row=6, column=0, columnspan=2, sticky='WE')
L7 = Label(root, relief='raised')
L7.grid(row=6, column=3, columnspan=2, sticky='WE')
root.mainloop()
I need to print net and tax in L6 and L7 labels. Give me some clues how do it, please.
The simple way to do this is to give those labels their own textvariables.
I replaced your 3 count functions with a single function show_tax. We use lambda functions in each Button command to call show_tax with the desired tax rate. I've also made a few other minor changes.
import tkinter as tk
def show_tax(rate):
b = gross.get()
n = round(b / rate, 2)
# Format to string with 2 digits after the decimal point
net.set(format(n, '.2f'))
t = round(b - n, 2)
tax.set(format(t, '.2f'))
root = tk.Tk()
root.geometry('310x165+250+250')
root.title('Tax calculator')
gross = tk.DoubleVar()
net = tk.StringVar()
tax = tk.StringVar()
tk.Label(root, text='Input gross amount').grid(row=0, column=0, columnspan=5)
e = tk.Entry(root, textvariable=gross)
e.grid(row=1, column=1, columnspan=3, sticky='WE', padx=5, pady=5)
tk.Label(root, text='Choose your tax rate').grid(row=2, column=0, columnspan=5)
b = tk.Button(root, text='5 %', command=lambda r=1.05: show_tax(r))
b.grid(row=3, column=0, padx=5, pady=5)
b = tk.Button(root, text='8 %', command=lambda r=1.08: show_tax(r))
b.grid(row=3, column=2, padx=5, pady=5)
b = tk.Button(root, text='23 %', command=lambda r=1.23: show_tax(r))
b.grid(row=3, column=4, padx=5, pady=5)
# An empty Label to force row to be displayed
tk.Label(root).grid(row=4, column=0, columnspan=5)
tk.Label(root, text='Net').grid(row=5, column=0, columnspan=2, sticky='WE')
tk.Label(root, text='TAX').grid(row=5, column=3, columnspan=2, sticky='WE')
l = tk.Label(root, textvariable=net, relief='raised')
l.grid(row=6, column=0, columnspan=2, sticky='WE')
l = tk.Label(root, textvariable=tax, relief='raised')
l.grid(row=6, column=3, columnspan=2, sticky='WE')
root.mainloop()
I have a couple more comments on your code (and my changes to it).
It's not a good idea to use from tkinter import * as that imports about 130 Tkinter names into the global namespace, which is messy and can lead to name collisions. Using the explicit tk. form makes the code easier to read.
BTW, the Widget .grid and .pack methods return None. So when you do something like
L2 = Label(root, text='Choose your tax rate').grid(row=2, column=0, columnspan=5)
it creates the label, puts it into the grid, and then sets L2 to None. If you need to keep a reference to the label you need to create the widget & place it into the grid in two steps, like this:
L2 = Label(root, text='Choose your tax rate')
L2.grid(row=2, column=0, columnspan=5)
If you don't need to keep a reference to the widget, but you still want to split it over 2 lines to keep the line length short then just use a "throwaway" variable, like I have with e, b, and l.
As Bryan Oakley mentions in the comments we don't actually need to give those labels their own StringVar textvariables: we can directly update their texts using the widget's .config method.
import tkinter as tk
def show_tax(rate):
b = gross.get()
n = round(b / rate, 2)
# Format to string with 2 digits after the decimal point
L6.config(text=format(n, '.2f'))
t = round(b - n, 2)
L7.config(text=format(t, '.2f'))
root = tk.Tk()
root.geometry('310x165+250+250')
root.title('Tax calculator')
gross = tk.DoubleVar()
tk.Label(root, text='Input gross amount').grid(row=0, column=0, columnspan=5)
e = tk.Entry(root, textvariable=gross)
e.grid(row=1, column=1, columnspan=3, sticky='WE', padx=5, pady=5)
tk.Label(root, text='Choose your tax rate').grid(row=2, column=0, columnspan=5)
b = tk.Button(root, text='5 %', command=lambda r=1.05: show_tax(r))
b.grid(row=3, column=0, padx=5, pady=5)
b = tk.Button(root, text='8 %', command=lambda r=1.08: show_tax(r))
b.grid(row=3, column=2, padx=5, pady=5)
b = tk.Button(root, text='23 %', command=lambda r=1.23: show_tax(r))
b.grid(row=3, column=4, padx=5, pady=5)
# An empty Label to force row to be displayed
tk.Label(root).grid(row=4, column=0, columnspan=5)
tk.Label(root, text='Net').grid(row=5, column=0, columnspan=2, sticky='WE')
tk.Label(root, text='TAX').grid(row=5, column=3, columnspan=2, sticky='WE')
L6 = tk.Label(root, relief='raised')
L6.grid(row=6, column=0, columnspan=2, sticky='WE')
L7 = tk.Label(root, relief='raised')
L7.grid(row=6, column=3, columnspan=2, sticky='WE')
root.mainloop()

tkinter in tkinter makes value disappear (python 3.4.3)

I wrote this piece of code, which is supposed to ask a user if all of his files have the same date and if yes, that he should write his date into a grid.
After entering the dates both windows should disappear and i want to keep the date.
Unfortunately I don't manage to let the first Input-Box disappear and after this whole procedure the entry date is [ ] again.
from tkinter import *
entry_date = []
if amountfiles == 1:
def moredates():
master.destroy()
def setdate():
def entry_date():
entry_date = e1.get()
entry_date = str(entry_date)
print("Date for all files is: ",entry_date)
master.destroy()
def quit():
sys.exit()
master = Tk()
Label(master, text="Please enter date (format YYYYMMDD, i.e. 20160824): ").grid(row=0)
e1 = Entry(master)
e1.grid(row=0, column=1)
Button(master, text='Quit', command=master.destroy).grid(row=3, column=1, sticky=W, pady=4)
Button(master, text='Insert', command=entry_date).grid(row=2, column=1, sticky=W, pady=4)
mainloop( )
master = Tk()
Label(master, text="Do all files have the same date?").grid(row=0)
Button(master, text='No...', command=moredates).grid(row=2, column=0, sticky=W, pady=4)
Button(master, text='Yes!', command=setdate).grid(row=1, column=0, sticky=W, pady=4)
Button(master, text='Close & Contiune', command=master.destroy).grid(row=3, column=0, sticky=W, pady=4)
mainloop( )
As the outer master variable is re-assigned in the function setdate(), the call master.destroy() will only close the new master, not the outer master. Try modifying the function setdate() as below:
def setdate():
def append_date():
date = e1.get() # get the input entry date
entry_date.append(date) # save the input date
print("Date for all files is: ", date)
master.destroy()
top = Toplevel() # use Toplevel() instead of Tk()
Label(top, text="Please enter date (format YYYYMMDD, i.e. 20160824): ").grid(row=0)
e1 = Entry(top)
e1.grid(row=0, column=1)
Button(top, text='Quit', command=master.destroy).grid(row=3, column=1, sticky=W, pady=4)
Button(top, text='Insert', command=append_date).grid(row=2, column=1, sticky=W, pady=4)
master.wait_window(top) # use Tk.wait_window()

Categories

Resources