How to print values into a Label in Tkinter - python

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()

Related

BMI Calculator program with Tkinter()

I want to create a BMI calculator program with Tkinter but I'm stuck at calculation procedure
I use StringVar() to keep user data to calculate but I don't know how to calculate
this my code :
from tkinter import *
def mainwindow():
main = Tk()
main.geometry("300x400")
main.title("BMI")
main.rowconfigure((0,1,2,3,4), weight=1)
main.columnconfigure(0, weight=1)
main.config(bg="green")
main.option_add("*Font", "times 15 bold")
return main
def createframe(main):
Label(main, text="BMI APP", bg="lightgreen").grid(row=0, column=0, sticky=N)
frame_1 = Frame(main, bg="white")
frame_1.grid(row=1, column=0, sticky="NEWS", padx=10, pady=10, ipady=5)
frame_2 = Frame(main, bg="white")
frame_2.grid(row=2, column=0, sticky="NEWS", padx=10, pady=10, ipady=5)
frame_3 = Frame(main, bg="white")
frame_3.grid(row=3, column=0, sticky="NEWS", padx=10, pady=10, ipady=20)
frame_bottom = Frame(main, bg="white")
frame_bottom.grid(row=4, column=0, sticky="NEWS", padx=10, pady=10, ipady=20)
frame_bottom.columnconfigure(0, weight=0)
frame_bottom.columnconfigure(1, weight=2)
return frame_1, frame_2, frame_3, frame_bottom
def widget(frame_1, frame_2, frame_3, frame_bottom):
Label(frame_1, text="HEIGHT:(cm.)").grid(row=0, column=0, padx=5, pady=5, sticky=W)
ent_height = Entry(frame_1, bg="pink", textvariable=height_var)
ent_height.grid(row=1, column=0, ipadx=40, padx=10, sticky=N+W)
Label(frame_2, text="WEIGHT:(kg.)").grid(row=0, column=0, padx=5, pady=5, sticky=W)
ent_weight = Entry(frame_2, bg="lightblue", textvariable=weight_var)
ent_weight.grid(row=1, column=0, ipadx=40, padx=10, sticky=N+W)
Button(frame_bottom, text="Calculate", highlightbackground="lightgreen", fg="white", command=find_bmi).grid(row=2, column=1)
show_data = Label(frame_bottom, bg="white")
return ent_height, ent_weight
def find_bmi():
global bmi
bmi = 0
height = height_var.get()
weight = weight_var.get()
height = float(height) / 100.0
bmi = float(weight) / height ** 2
print("BMI = %0.2f" % bmi)
bmi = 0
main = mainwindow()
height_var = StringVar()
height_var.set("1")
weight_var = StringVar()
weight_var.set("1")
frame_1, frame_2, frame_3, frame_bottom = createframe(main)
ent_height, ent_weight = widget(frame_1, frame_2, frame_3, frame_bottom)
find_bmi()
main.mainloop()
I try to set a new value and calculate it because StringVar() can't calculate itself but when I use it that way I have to set the default to 1 if I don't set it will error ZeroDivisionError: float division by zero I don't want to set a number first if I set the first user will see that number
the frame_3 is used to show BMI to the user when calculating completed
You can check to see if the height and weight inputs have been filled in before doing the conversion/calculation.
from tkinter import *
def mainwindow():
main = Tk()
main.geometry("300x400")
main.title("BMI")
main.rowconfigure((0,1,2,3,4), weight=1)
main.columnconfigure(0, weight=1)
main.config(bg="green")
main.option_add("*Font", "times 15 bold")
return main
def createframe(main):
Label(main, text="BMI APP", bg="lightgreen").grid(row=0, column=0, sticky=N)
frame_1 = Frame(main, bg="white")
frame_1.grid(row=1, column=0, sticky="NEWS", padx=10, pady=10, ipady=5)
frame_2 = Frame(main, bg="white")
frame_2.grid(row=2, column=0, sticky="NEWS", padx=10, pady=10, ipady=5)
frame_3 = Frame(main, bg="white")
frame_3.grid(row=3, column=0, sticky="NEWS", padx=10, pady=10, ipady=20)
frame_bottom = Frame(main, bg="white")
frame_bottom.grid(row=4, column=0, sticky="NEWS", padx=10, pady=10, ipady=20)
frame_bottom.columnconfigure(0, weight=0)
frame_bottom.columnconfigure(1, weight=2)
return frame_1, frame_2, frame_3, frame_bottom
def widget(frame_1, frame_2, frame_3, frame_bottom):
Label(frame_1, text="HEIGHT:(cm.)").grid(row=0, column=0, padx=5, pady=5, sticky=W)
ent_height = Entry(frame_1, bg="pink", textvariable=height_var)
ent_height.grid(row=1, column=0, ipadx=40, padx=10, sticky=N+W)
Label(frame_2, text="WEIGHT:(kg.)").grid(row=0, column=0, padx=5, pady=5, sticky=W)
ent_weight = Entry(frame_2, bg="lightblue", textvariable=weight_var)
ent_weight.grid(row=1, column=0, ipadx=40, padx=10, sticky=N+W)
Label(frame_3, text="BMI").grid(row=0, column=0, padx=5, pady=5,sticky=W)
show_data = Label(frame_3)
show_data.grid(row=1, column=0, ipadx=40, padx=10, sticky=N+W)
Button(frame_bottom, text="Calculate", highlightbackground="lightgreen", fg="white", command=find_bmi).grid(row=2, column=1)
return ent_height, ent_weight, show_data
def find_bmi():
height = height_var.get()
weight = weight_var.get()
# check height and weight filled in
if height and weight:
height = float(height) / 100.0
bmi = round(float(weight) / height ** 2, 2)
show_data.config(text = bmi)
else:
show_data.config(text='')
main = mainwindow()
height_var = StringVar()
weight_var = StringVar()
frame_1, frame_2, frame_3, frame_bottom = createframe(main)
ent_height, ent_weight, show_data = widget(frame_1, frame_2, frame_3, frame_bottom)
main.mainloop()

tkinter resize GUI on different monitors

I am mainly coding on my MAC.
I created a GUI that is used for a tool I am using to automate things with selenium.
I have used .grid for all widgets in my GUI.
But when I open the GUI on my Windows laptop at home (same resolution but much smaller monitor panel) it is totally messed up.
Here are two screenshot showing the problem,
Messed up layout on Win Laptop (17,3")
The second screenshot shows how it should look.
This is the code I used for the grid layout:
# General GUI settings
app = Tk()
app.title('trade_buddy')
app.geometry('605x800')
app.minsize(605, 800)
app.maxsize(605, 800)
app.grid_rowconfigure(0, weight=1)
app.grid_rowconfigure(1, weight=1)
app.grid_rowconfigure(2, weight=1)
app.grid_rowconfigure(3, weight=1)
app.grid_rowconfigure(4, weight=1)
app.grid_rowconfigure(5, weight=1)
app.grid_rowconfigure(6, weight=1)
app.grid_rowconfigure(7, weight=1)
app.grid_rowconfigure(8, weight=1)
app.grid_rowconfigure(9, weight=1)
app.grid_rowconfigure(10, weight=1)
app.grid_rowconfigure(11, weight=1)
app.grid_rowconfigure(12, weight=1)
app.grid_rowconfigure(13, weight=1)
#Background label
image = Image.open('v2.0/lolo.png')
image = image.resize((600,450), Image.ANTIALIAS)
copy_of_image = image.copy()
photo = ImageTk.PhotoImage(image)
label = tk.Label(app, image = photo)
label.place(x=0, y=0)
#Buttons
b_init = tk.Button(app,text='Initialize',font='Tahoma 10 bold',bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d',padx=8, pady=10, command=lambda:threading.Thread(target=tb,daemon=True).start())
b_exit = tk.Button(app,text='Exit',font='Tahoma 10 bold',padx=8,bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d', pady=10,command=lambda:threading.Thread(target=exit_tb,daemon=True).start())
b_start = tk.Button(app,text='Start',font='Tahoma 10 bold',bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d',padx=8, pady=10,command=lambda:threading.Thread(target=filters,daemon=True).start())
b_pause = tk.Button(app,text='Pause',font='Tahoma 10 bold',bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d',padx=8, pady=10,command=lambda:threading.Thread(target=stop_tb,daemon=True).start())
b_tfm = tk.Button(app,text='TFM',font='Tahoma 10 bold',bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d',padx=8, pady=10,command=lambda:threading.Thread(target=tfm,daemon=True).start())
#Labels
l_maxBO = tk.Label(app,text='Maximum buy price:',bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10')
l_itemsontf = tk.Label(text='# of items on transfer list:',bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10')
l_speed = tk.Label(text='Choose speed:',bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10 bold')
l_routine = tk.Label(text='Choose routine:',bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10 bold')
#Entries
e_maxBO = tk.Entry(app, width=10, bg='#1e1e1f', fg='#f8f09d', font='Tahoma 10')
e_itemsontf = tk.Entry(app, width=10, bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10')
e_fixedsellprice = tk.Entry(app, width=10, bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10')
#Text box
t_outputbox = tk.Text(app, width=99, height=27, font='Tahoma 10',bg='#2c2c2c', fg='#f8f09d', relief=SUNKEN, highlightthickness="1")
#Grid Layout
l_maxBO.grid(row=0, column=0, sticky='w', padx=5, pady=5)
l_itemsontf.grid(row=1, column=0, sticky='w', padx=5, pady=5)
l_speed.grid(row=3, column=0, sticky='w', padx=5, pady=1, ipady=1)
l_routine.grid(row=7, column=0, sticky='w', padx=5, pady=1, ipady=1)
e_maxBO.grid(row=0, column=1, sticky='w', padx=5, pady=5)
e_itemsontf.grid(row=1, column=1, sticky='w', padx=5, pady=5)
e_fixedsellprice.grid(row=11, column=0, sticky='w', padx=5, pady=3)
b_exit.grid(row=12, column=8, sticky='sw', padx=5, pady=10)
b_init.grid(row=12, column=4, sticky='sw', padx=5, pady=10)
b_start.grid(row=12, column=0, sticky='sw', padx=5, pady=10)
b_pause.grid(row=12, column=1, sticky='sw', padx=5, pady=10)
b_tfm.grid(row=12, column=2, sticky='sw', padx=5, pady=10)
r_normal.grid(row=4, column=0, sticky='w', padx=5, pady=1)
r_fast.grid(row=5, column=0, sticky='w', padx=5, pady=1)
r_slow.grid(row=6, column=0, sticky='w', padx=5, pady=1)
r_buyonly.grid(row=8, column=0, sticky='w', padx=5, pady=1)
r_fullroutine.grid(row=9, column=0, sticky='w', padx=5, pady=1)
r_buysellfixed.grid(row=10, column=0, sticky='w', padx=5, pady=1)
t_outputbox.grid(row=13, column=0, columnspan=13, rowspan=13, sticky='nsew', padx=5, pady=10)
As a coding beginner, I really have no idea what else I could change.
I already changed from .place to .grid but the problem is still the same.
Does anyone have an idea how I could setup my GUI that it keeps the minimum required geometry relations no matter on what monitor I work?
Here is an example of forcing it to look like the second picture.
import tkinter as tk
from PIL import ImageTk, Image
# General GUI settings
app = tk.Tk()
app.configure(bg="black")
#Background label
image = Image.open('test.png')
image = image.resize((200,200), Image.ANTIALIAS)
copy_of_image = image.copy()
photo = ImageTk.PhotoImage(image)
label = tk.Label(app, image = photo)
label.grid(row=3, column=1, sticky='w')
#others
r_normal = tk.Radiobutton(app, text="Normal Speed")
r_fast = tk.Radiobutton(app, text="Fast Speed")
r_slow = tk.Radiobutton(app, text="Slow Speed")
r_buyonly = tk.Radiobutton(app, text="Buy only")
r_fullroutine = tk.Radiobutton(app, text="Full routine (optimized price)")
r_buysellfixed = tk.Radiobutton(app, text="Buy and sell for fixed price")
#Buttons
b_init = tk.Button(app,text='Initialize',font='Tahoma 10 bold',bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d',padx=8, pady=10, command=lambda:threading.Thread(target=tb,daemon=True).start())
b_exit = tk.Button(app,text='Exit',font='Tahoma 10 bold',padx=8,bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d', pady=10,command=lambda:threading.Thread(target=exit_tb,daemon=True).start())
b_start = tk.Button(app,text='Start',font='Tahoma 10 bold',bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d',padx=8, pady=10,command=lambda:threading.Thread(target=filters,daemon=True).start())
b_pause = tk.Button(app,text='Pause',font='Tahoma 10 bold',bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d',padx=8, pady=10,command=lambda:threading.Thread(target=stop_tb,daemon=True).start())
b_tfm = tk.Button(app,text='TFM',font='Tahoma 10 bold',bg='#f8f09d',fg='#1e1e1f',activebackground='#1e1e1f',activeforeground='#f8f09d',padx=8, pady=10,command=lambda:threading.Thread(target=tfm,daemon=True).start())
#Labels
l_maxBO = tk.Label(app,text='Maximum buy price:',bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10')
l_itemsontf = tk.Label(text='# of items on transfer list:',bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10')
l_speed = tk.Label(text='Choose speed:',bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10 bold')
l_routine = tk.Label(text='Choose routine:',bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10 bold')
#Entries
e_maxBO = tk.Entry(app, width=10, bg='#1e1e1f', fg='#f8f09d', font='Tahoma 10')
e_itemsontf = tk.Entry(app, width=10, bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10')
e_fixedsellprice = tk.Entry(app, width=10, bg='#1e1e1f', fg='#f8f09d',font='Tahoma 10')
#Text box
t_outputbox = tk.Text(app, width=99, height=27, font='Tahoma 10',bg='#2c2c2c', fg='#f8f09d', relief=tk.SUNKEN, highlightthickness="1")
#Grid Layout
l_maxBO.grid(row=0, column=0, sticky='w', padx=5, pady=5)
l_itemsontf.grid(row=1, column=0, sticky='w', padx=5, pady=5)
l_speed.grid(row=3, column=0, sticky='w', padx=5, pady=1, ipady=1)
l_routine.grid(row=7, column=0, sticky='w', padx=5, pady=1, ipady=1)
e_maxBO.grid(row=0, column=1, sticky='w', padx=5, pady=5)
e_itemsontf.grid(row=1, column=1, sticky='w', padx=5, pady=5)
e_fixedsellprice.grid(row=11, column=0, sticky='w', padx=5, pady=3)
b_exit.grid(row=12, column=8, sticky='sw', padx=5, pady=10)
b_init.grid(row=12, column=4, sticky='sw', padx=5, pady=10)
b_start.grid(row=12, column=0, sticky='sw', padx=5, pady=10)
b_pause.grid(row=12, column=1, sticky='sw', padx=5, pady=10)
b_tfm.grid(row=12, column=2, sticky='sw', padx=5, pady=10)
r_normal.grid(row=4, column=0, sticky='w', padx=5, pady=1)
r_fast.grid(row=5, column=0, sticky='w', padx=5, pady=1)
r_slow.grid(row=6, column=0, sticky='w', padx=5, pady=1)
r_buyonly.grid(row=8, column=0, sticky='w', padx=5, pady=1)
r_fullroutine.grid(row=9, column=0, sticky='w', padx=5, pady=1)
r_buysellfixed.grid(row=10, column=0, sticky='w', padx=5, pady=1)
t_outputbox.grid(row=13, column=0, columnspan=13, rowspan=13, sticky='nsew', padx=5, pady=10)
Notable differences:
I had to set a background color to make up for how we are moving that image.
The image is no longer using .place and instead using .grid.
The image will need to be resized a bit differently because it is a smaller area.
I removed all those row_configures because they were removing some rigidity, you can add it back if you like, but you'll have to re-scale your columns to match the new layout.
Let us know if you have any questions etc.

ValueError: could not convert string to float: in tkinter

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()

Dynamically fit tkinter window to its content

I have a Toplevel Window with one grid row containing a Label, Entry and a "+" Button (window on startup)
When I hit the Add-Button a new row with the same content is generated. But the problem is, that the window doesn't resize and fit to its new contents. Should look like this resized window.
The code is below:
def process_map():
numbers = {0:'\u2080', 1:'\u2081', 2:'\u2082', 3:'\u2083', 4:'\u2084', 5:'\u2085', 6:'\u2086', 7:'\u2087', 8:'\u2088', 9:'\u2089'}
button_pos = tk.IntVar(0)
ENTRIES = {}
def add_button():
if button_pos.get() >= 10:
index = numbers[button_pos.get()//10] + numbers[button_pos.get()%10]
else:
index = numbers[button_pos.get()]
lb = tk.Label(top_root, text='\u03C6'+index)
lb.grid(row=button_pos.get(), column=0, sticky='NWES')
entry = tk.Entry(top_root, width=4, relief='sunken', bd=2)
entry.grid(row=button_pos.get(), column=1, sticky='WE', padx=5, pady=5)
ENTRIES.update({button_pos.get():entry})
bt.grid(row=button_pos.get(), column=2, sticky='WE', padx=5, pady=5)
bt_close.grid(row=button_pos.get()+1, column=1, padx=5, pady=5)
bt_start.grid(row=button_pos.get()+1, column=0, padx=5, pady=5)
button_pos.set(button_pos.get()+1)
center(top_root)
top_root = tk.Toplevel(root)
top_root.title('Select \u03C6')
lb = tk.Label(top_root, text='\u03C6\u2081', height=1)
lb.grid(row=0, column=0, sticky='NWES')
entry = tk.Entry(top_root, width=4, relief='sunken', bd=2)
entry.grid(row=0, column=1, sticky='WE', padx=5, pady=5)
button_pos.set(button_pos.get()+2)
ENTRIES.update({button_pos.get():entry})
bt = tk.Button(top_root, text='+', command=add_button,)
bt.grid(row=0, column=2, sticky='WE', padx=5, pady=5)
bt_close = tk.Button(top_root, text='Cancel', width=15, command=top_root.destroy)
bt_close.grid(row=button_pos.get()+1, column=1, padx=5, pady=5)
bt_start = tk.Button(top_root, text='Start', width=15)
bt_start.grid(row=button_pos.get()+1, column=0, padx=5, pady=5)
center(top_root)
top_root.mainloop()

How can I prevent Toplevel() from opening two additional windows?

I have a program that uses Tkinter and I'm trying to assign a command to a button in my root window that opens one additional window. I'm using Toplevel(), but whenever I click the button I've assigned the command to, two windows open, one with my root window's name and one with the name of the additional window I've assigned.
I've tried using .withdraw and .destroy, to hide or remove this extra root window, but nothing seems to be working.
Here is my code:
import Tkinter
from Tkinter import *
root = Tk()
root.wm_title("VACS")
# # Top label # #
SetParameters = Label(text="Set Parameters", width=110, relief=RIDGE)
SetParameters.grid(row=1, column=0, columnspan=7, padx=5, pady=5)
# # Spatial freq settings # #
SpatialFreq = Label(text="Spatial Frequency", width=15, relief=RIDGE)
SpatialFreq.grid(row=3, column=0, padx=5, pady=5)
From1 = Label(text="from")
From1.grid(row=3, column=1, padx=5, pady=5)
Select1 = Spinbox(from_=0, to=10, width=25)
Select1.grid(row=3, column=2, padx=5, pady=5)
To1 = Label(text="to")
To1.grid(row=3, column=3, padx=5, pady=5)
Select2 = Spinbox(from_=0, to=10, width=25)
Select2.grid(row=3, column=4, padx=5, pady=5)
Steps = Label(text="in steps of")
Steps.grid(row=3, column=5, padx=5, pady=5)
Select3 = Spinbox(from_=0, to=10, width=25)
Select3.grid(row=3, column=6, padx=5, pady=5)
# # Contrast settings # #
Contrast = Label(text="Contrast", width=15, relief=RIDGE)
Contrast.grid(row=5, column=0, padx=5, pady=5)
From2 = Label(text="from")
From2.grid(row=5, column=1, padx=5, pady=5)
Select4 = Spinbox(from_=0, to=10, width=25)
Select4.grid(row=5, column=2, padx=5, pady=5)
To2 = Label(text="to")
To2.grid(row=5, column=3, padx=5, pady=5)
Select5 = Spinbox(from_=0, to=10, width=25)
Select5.grid(row=5, column=4, padx=5, pady=5)
Steps2 = Label(text="in steps of")
Steps2.grid(row=5, column=5, padx=5, pady=5)
Select6 = Spinbox(from_=0, to=10, width=25)
Select6.grid(row=5, column=6, padx=5, pady=5)
# # Test button # #
Test = Button(text="Begin Test", width=25, command=Top)
Test.grid(row=6, column=0, columnspan=7, pady=5)
# # Directory input window # #
def Top():
Toplevel()
Toplevel().wm_title("Directory")
root.mainloop()
If you click "Begin Test" in the root window, two extras pop up. I only want the one that says "Directory."
Any ideas?
You're creating two, since Toplevel() is the constructor call:
Toplevel()
Toplevel().wm_title("Directory")
Instead, create one and save it:
top = Toplevel()
top.wm_title("Directory")

Categories

Resources