How to work with Values entered through Tkinter entry widgets - python-3.x

I'm creating this program to calculate the weight of animals in a camp, by getting the amount of animals of each age and then get the total amount of food they need daily.
I'm using Tkinter for the GUI where the amount of animals of each age is entered.
When i run the program the program doesn't retrieve the values that where entered and doesn't work with them?
I am completely new to Tkinter and fairly new to Python 3.6
I would be extremely grateful for any constructive criticism.
#Beginning
from tkinter import *
from math import *
import string
root = Tk()
#Function to calculate everything- Gets total weight of animals and then calculates feed
def enter_click(event):
global SabCow, SabBull, BuffBull, BuffCow, RoanCow, RoanBull, Six_Months,
One_Year, Two_Year, Three_Year, Big
M1_int = IntVar(M1.get())
M2_int = IntVar(M2.get())
M3_int = IntVar(M3.get())
M4_int = IntVar(M4.get())
M5_int = IntVar(M5.get())
F1_int = IntVar(F1.get())
F2_int = IntVar(F2.get())
F3_int = IntVar(F3.get())
F4_int = IntVar(F4.get())
F5_int = IntVar(F5.get())
#Work with which animal is selected form radiobutton, then calculate what is the weight of animals of each age then calculate food necessary
if A.get() == 1 :
f1_weight = F1_int * ((SabCow * 25)/Six_Months)
f2_weight = F2_int * ((SabCow * 40)/One_Year)
f3_weight = F3_int * ((SabCow * 70)/Two_Year)
f4_weight = F4_int * ((SabCow * 85)/Three_Year)
f5_weight = F5_int * SabCow
m1_weight = M1_int * ((SabBull * 25)/Six_Months)
m2_weight = M2_int * ((SabBull * 40)/One_Year)
m3_weight = M3_int * ((SabBull * 70)/Two_Year)
m4_weight = M4_int * ((SabBull * 85)/Three_Year)
m5_weight = M5_int * SabBull
Weight_Female = lambda f1_weight, f2_weight, f3_weight, f4_weight, f5_weight : f1_weight + f2_weight + f3_weight + f4_weight + f5_weight
Weight_Male = m1_weight + m2_weight + m3_weight + m4_weight + m5_weight
Total_Weight = Weight_Female + Weight_Male
Total_Food = Total_Weight * Big
animal = "Sable"
result_text = animal, "\nTotalFood Requierd: ", Total_Food, "\n", Total_Weight, "\n", Weight_Female, "\n", Weight_Male
return result_text
elif A.get() == 2 :
f1_weight = F1_int * ((BuffCow * 25)/Six_Months)
f2_weight = F2_int * ((BuffCow * 40)/One_Year)
f3_weight = F3_int * ((BuffCow * 70)/Two_Year)
f4_weight = F4_int * ((BuffCow * 85)/Three_Year)
f5_weight = F5_int * SabCow
m1_weight = M1_int * ((BuffBull * 25)/Six_Months)
m2_weight = M2_int * ((BuffBull * 40)/One_Year)
m3_weight = M3_int * ((BuffBull * 70)/Two_Year)
m4_weight = M4_int * ((BuffBull * 85)/Three_Year)
m5_weight = M5_int * BuffBull
Weight_Female = f1_weight + f2_weight + f3_weight + f4_weight + f5_weight
Weight_Male = m1_weight + m2_weight + m3_weight + m4_weight + m5_weight
Total_Weight = Weight_Female + Weight_Male
Total_Food = Total_Weight * Big
animal = "Buffalo"
result_text = animal, "\nTotalFood Requierd: ", Total_Food, "\n", Total_Weight, "\n", Weight_Female, "\n", Weight_Male
return result_text
elif A.get() == 3 :
f1_weight = F1_int * ((RoanCow * 25)/Six_Months)
f2_weight = F2_int * ((RoanCow * 40)/One_Year)
f3_weight = F3_int * ((RoanCow * 70)/Two_Year)
f4_weight = F4_int * ((RoanCow * 85)/Three_Year)
f5_weight = F5_int * RoanCow
m1_weight = M1_int * ((RoanBull * 25)/Six_Months)
m2_weight = M2_int * ((RoanBull * 40)/One_Year)
m3_weight = M3_int * ((RoanBull * 70)/Two_Year)
m4_weight = M4_int * ((RoanBull * 85)/Three_Year)
m5_weight = M5_int * RoanBull
Weight_Female = f1_weight + f2_weight + f3_weight + f4_weight + f5_weight
Weight_Male = m1_weight + m2_weight + m3_weight + m4_weight + m5_weight
Total_Weight = Weight_Female + Weight_Male
Total_Food = Total_Weight * Big
animal = "Roan"
result_text = animal, "\nTotalFood Requierd: ", Total_Food, "\n", Total_Weight, "\n", Weight_Female, "\n", Weight_Male
return result_text
print(result_text)
animal = StringVar()
#Animal Weight
BuffBull = 750
BuffCow = 650
SabBull = 230
SabCow = 210
RoanBull = 270
RoanCow = 240
#Animal Ages to Weight
Six_Months = 125
One_Year = 140
Two_Year = 170
Three_Year = 185
#Percentage Food needed of total KG
Big = 2/102
Small = 5/105
#Tkinter
A = IntVar()
A.set(1)
result_text = StringVar()
f1_weight = DoubleVar()
f2_weight = DoubleVar()
f3_weight = DoubleVar()
f4_weight = DoubleVar()
f5_weight = DoubleVar()
m1_weight = DoubleVar()
m2_weight = DoubleVar()
m3_weight = DoubleVar()
m4_weight = DoubleVar()
m5_weight = DoubleVar()
#GUI
w =Label(root, text="Choose an Animal:", justify=LEFT, padx=5,pady=10).grid(row=0)
o =Label(root, text="Results:", justify=LEFT, padx=5, pady=10).grid(row=7)
Label(root, text="Age", padx=5, pady=20).grid(row=0, column=2)
Label(root, text="M", padx=5, pady=20).grid(row=0, column=3)
Label(root, text="F", padx=5, pady=20).grid(row=0, column=4)
Radiobutton(root, text="Sable", padx=20, variable=A, value=1).grid(row=1)
Radiobutton(root, text="Buffalo", padx=20, variable=A, value=2).grid(row=2)
Radiobutton(root, text="Roan", padx=20, variable=A, value=3).grid(row=3)
Label(root, text="6 Months :").grid(row=1, column=2)
Label(root, text="1 Year :").grid(row=2, column=2)
Label(root, text="2 Years :").grid(row=3, column=2)
Label(root, text="3 Years :").grid(row=4, column=2)
Label(root, text="4 Years :").grid(row=5, column=2)
#Entry widgets-to get total of animals of each age
M1 = Entry(root)
M2 = Entry(root)
M3 = Entry(root)
M4 = Entry(root)
M5 = Entry(root)
F1 = Entry(root)
F2 = Entry(root)
F3 = Entry(root)
F4 = Entry(root)
F5 = Entry(root)
M1.grid(row=1, column=3)
M2.grid(row=2, column=3)
M3.grid(row=3, column=3)
M4.grid(row=4, column=3)
M5.grid(row=5, column=3)
F1.grid(row=1, column=4)
F2.grid(row=2, column=4)
F3.grid(row=3, column=4)
F4.grid(row=4, column=4)
F5.grid(row=5, column=4)
#Calculation button and event
enter_button=Button(root, text="Enter")
enter_button.grid(row=6)
enter_button.bind("<Enter>",enter_click)
enter_button.bind("<Return>",enter_click)
root.mainloop()
At this stage I've scouted the internet for 2 weeks with no help and now I also get this error when running the program:
AttributeError: 'str' object has no attribute '_root'

There is a multiple problems in your code.
First:
M1_int = IntVar(M1.get())
Should be like:
M1_int = float(M1.get())
(it is for all variables in M1...F7)
Second: in Weight_Female calculation you doesn't need lambda.
Third:A == 3 is always False. You need to get value form control like in first case (A.get() == 1).

Related

AttributeError: 'IAPWS97' object has no attribute 'rho'

I am trying to run this loop; however, I am getting a no attribute error in the second portion of my code. Below is the entire code (sorry for the length). When I run the first case (PWR) the code executes normally as expected. However, when I run the second case (BWR) I receive the error even though it is the same exact statement from case one. Is there any fix or explanation for this? Thank you.
import numpy as np
import math
from iapws import IAPWS97
import matplotlib.pyplot as plt
case = int(input('Which case [1 (PWR) or 2 (BWR)]? '))
if case == 1: # PWR
H = 3.8 # m
He = 3.8 # m
Pitch = 1.25 * 10 ** (-2) # m
Gap_t = 0.00006 # m
D_fuel = 0.0082 # m
k_gap = 0.25 # W/m-K
k_c = 21.5 # W/m-K
k_fuel = 3.6 # W/m-K
T0 = float(278 + 273.15) # K
q0_prime = float(330 * 10 ** (2)) # W/m
P0 = 15 # MPa
MF = float(3460) # kg/m^2-s
D_rod = .0095 # m
R_rod = D_rod / 2
R_fuel = D_fuel / 2
R_gap = R_fuel + Gap_t
R_clad = R_rod
Clad_t = D_rod - D_fuel - Gap_t # m
h0_enthalpy = (IAPWS97(T=T0, P=P0).h) * 10 ** (3)
T_sat0 = IAPWS97(P=P0, x=0).T
g = 9.81 # m/s
# geometry properties
heated_p = math.pi * D_rod
wetted_p = math.pi * D_rod
A_f = (Pitch ** 2) - ((1 / 4) * math.pi * (D_rod ** 2))
D_H = (4 * A_f) / heated_p
# grid setup
grid_points = 100
dz = H / grid_points
z_array = np.arange(0, H, dz)
z_arrayplots = np.arange(0, H, dz)
q_HeatFluxList = []
# defining array of q'' values in list
for z in z_array:
heat_fluxA = (q0_prime / (math.pi * D_rod)) * math.sin(math.pi * (z / He))
q_HeatFluxList.append(heat_fluxA)
q_heat_flux = np.array(q_HeatFluxList)
q_prime = np.zeros(len(z_array))
for i in range(0, len(z_array)):
q_prime[i] = q0_prime * math.sin((np.pi * z_array[i]) / He)
# defining array of h values
h_enthalpy_list = []
h_enthalpy_prefactor = ((heated_p * q0_prime * H) / (A_f * MF * (math.pi ** 2) * D_rod))
for z in z_array:
h_enthalpy = (-h_enthalpy_prefactor * math.cos(math.pi * (z / He))) + h_enthalpy_prefactor + h0_enthalpy
h_enthalpy_list.append(h_enthalpy)
h_enthalpy_array_J = np.array(h_enthalpy_list)
h_enthalpy_array = h_enthalpy_array_J * 10 ** (-3)
P_array = np.zeros(len(z_array))
P_array[0] = P0
T_sat = np.zeros(len(z_array))
T_sat[0] = T_sat0
T_f_array = np.zeros(len(z_array))
T_f_array[0] = T0
Re = np.zeros(len(z_array))
Re_f = np.zeros(len(z_array))
Pr = np.zeros(len(z_array))
k_fluid = np.zeros(len(z_array))
x_array = np.zeros(len(z_array))
xe_array = np.zeros(len(z_array))
frictional = np.zeros(len(z_array))
gravitational = np.zeros(len(z_array))
compressibility = np.zeros(len(z_array))
# Pressure Loop PWR
dp = 0.001
for i in range(0, len(z_array) - 1):
rho_f = IAPWS97(P=P_array[i], x=0).rho
vf = IAPWS97(P=P_array[i], x=0).v
vg = IAPWS97(P=P_array[i], x=1).v
hf_enthalpy = IAPWS97(P=P_array[i], x=0).h
hg_enthalpy = IAPWS97(P=P_array[i], x=1).h
muf = (IAPWS97(P=P_array[i], x=0).mu) * 10 ** (-6)
mug = (IAPWS97(P=P_array[i], x=1).mu) * 10 ** (-6)
k_fluid[i] = IAPWS97(P=P_array[i], T=T_f_array[i]).k
Pr[i] = IAPWS97(P=P_array[i], h=h_enthalpy_array[i]).Liquid.Prandt
x_array[i] = 0
xe_array[i] = (h_enthalpy_array[i] - hf_enthalpy) / (hg_enthalpy - hf_enthalpy)
rho_m = 1 / ((x_array[i] * vg) + ((1 - x_array[i]) * vf))
mu_m = 1 / ((x_array[i] / mug) + ((1 - x_array[i]) / muf))
Re[i] = (MF * D_H) / (mu_m * 10 ** 6) # convert mu to Pa/s
f = 0.079 * (Re[i] ** -0.25) * (mu_m / muf)
Tau = (1 / 2) * f * ((MF ** 2) / rho_m)
Re_f[i] = Re[i]
vf_plus_dP = IAPWS97(P=P_array[i] + dp, x=0).v
vf_minus_dP = IAPWS97(P=P_array[i] - dp, x=0).v
ddP_vf = (vf_plus_dP - vf_minus_dP) / (2 * (dp * 10 ** 6))
frictional[i] = (Tau * wetted_p) / A_f
gravitational[i] = g * rho_f
compressibility[i] = (MF ** 2) * (ddP_vf)
dPdz_num = (frictional[i] + gravitational[i]) # Pa/m
dPdz_denom = 1 + compressibility[i] # Pa/m
dPdz = -dPdz_num / dPdz_denom # Pa/m
P_array[i + 1] = P_array[i] + ((dPdz * dz) * 10 ** (-6))
T_f_array[i + 1] = IAPWS97(P=P_array[i + 1], h=h_enthalpy_array[i + 1]).T
T_sat[i + 1] = IAPWS97(P=P_array[i + 1], x=0).T
# final calc for final value of quality and void fraction because loop stops before these
hf_final = IAPWS97(P=P_array[-1], x=0).h
hg_final = IAPWS97(P=P_array[-1], x=1).h
muf_final = (IAPWS97(P=P_array[-1], x=0).mu) * 10 ** (-6)
mug_final = (IAPWS97(P=P_array[-1], x=1).mu) * 10 ** (-6)
k_fluid[-1] = IAPWS97(P=P_array[-1], T=T_f_array[-1]).k
xe_array[-1] = (h_enthalpy_array[-1] - hf_final) / (hg_final - hf_final)
# fuel and clad temps
T_C_Outer = np.zeros(len(z_array))
mu_m_final = 1 / ((x_array[-1] / mug_final) + ((1 - x_array[-1]) / muf_final))
Re_f[-1] = (MF * D_H) / (muf_final * 10 ** 6)
Pr[-1] = IAPWS97(P=P_array[i], h=h_enthalpy_array[i]).Liquid.Prandt
h_HT = 0.023 * (Re_f[0] ** 0.8) * (Pr[0] ** 0.4) * (k_fluid[0] / D_H)
T_C_Outer[0] = (q_heat_flux[0] + (h_HT * T_f_array[0])) / h_HT
for i in range(0, len(z_array) - 1):
h_HT = 0.023 * (Re_f[i + 1] ** 0.8) * (Pr[i + 1] ** 0.4) * (k_fluid[i + 1] / D_H)
T_C_Outer[i + 1] = (q_heat_flux[i + 1] + (h_HT * T_f_array[i + 1])) / h_HT
q_triple_prime = (q_prime * 4) / (np.pi * (D_fuel ** 2))
T_C_Inner = np.zeros(len(z_array))
T_F_Outer = np.zeros(len(z_array))
T_F_Center = np.zeros(len(z_array))
for i in range(0, len(z_array)):
C1 = -((q0_prime * R_clad) / (k_c * heated_p)) * np.sin(np.pi * (z_array[i] / H))
C2 = T_C_Outer[i] - (C1 * np.log(R_clad))
T_C_Inner[i] = (C1 * np.log(R_gap)) + C2
C3 = (k_c / k_gap) * C1
C4 = T_C_Inner[i] - (C3 * np.log(R_gap))
T_F_Outer[i] = (C3 * np.log(R_fuel)) + C4
C6 = T_F_Outer[i] + ((q_triple_prime[i] * (R_fuel ** 2)) / (4 * k_fuel))
T_F_Center[i] = C6
CL_max = np.amax(T_F_Center)
index = np.where(T_F_Center == CL_max)
z_CL_max = z_array[index]
Clad_max = np.amax(T_C_Inner)
index = np.where(T_C_Inner == Clad_max)
z_Clad_max = z_array[index]
plt.figure(1)
plt.plot(T_C_Outer, z_arrayplots, label='Clad Outer Surface Temp')
plt.plot(T_C_Inner, z_arrayplots, label='Clad Inner Surface Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempClad.png", dpi=600)
plt.figure(2)
plt.plot(T_C_Outer, z_arrayplots, label='Clad Outer Surface Temp')
plt.plot(T_C_Inner, z_arrayplots, label='Clad Inner Surface Temp')
plt.plot(T_F_Outer, z_arrayplots, label='Fuel Outer Surface Temp')
plt.plot(T_F_Center, z_arrayplots, label='Fuel Centerline Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempFuelAndClad.png", dpi=600)
# radial calcs
T_array_A = [T_F_Center[25], T_F_Outer[25], T_C_Inner[25], T_C_Outer[25]]
T_array_B = [T_F_Center[49], T_F_Outer[49], T_C_Inner[49], T_C_Outer[49]]
T_array_C = [T_F_Center[53], T_F_Outer[53], T_C_Inner[53], T_C_Outer[53]]
r_array = [0, R_fuel, R_gap, R_clad]
plt.figure(3)
plt.plot(r_array, T_array_A, label='z = -H/4 = -0.9 m')
plt.plot(r_array, T_array_B, label='z = 0 m')
plt.plot(r_array, T_array_C, '--', label='z = zmax = 0.108 m')
plt.legend(loc='upper left')
plt.ylabel("Temperature [K]")
plt.xlabel("Radius r [m]")
plt.savefig("TempRadial.png", dpi=600)
# critical heat flux and DNBR
P_array_DNBR = np.delete(P_array, 0)
q_heat_flux_DNBR = np.delete(q_heat_flux, 0)
z_arrayplots_DNBR = np.delete(z_arrayplots, 0)
G_Mlbs = MF * (((2.20462 * 10 ** (-6)) * 3600) / 10.7639)
q_heat_flux_MBtu = q_heat_flux[1:] * 3.41 * (1 / 1000000) * (1 / 10.7639)
P_c = 22.064 # https://nuclearstreet.com/nuclear-power-plants/w/nuclear_power_plants/features-of-pressurized-water-reactors
P_crit = P_array_DNBR / P_c
P1 = 0.5328
P2 = 0.1212
P3 = 1.6151
P4 = 1.4066
P5 = -0.3040
P6 = 0.4843
P7 = -0.3285
P8 = -2.0749
A = P1 * (P_crit ** P2) * (G_Mlbs ** (P5 + (P7 * P_crit)))
C = P3 * (P_crit ** P4) * (G_Mlbs ** (P6 + (P8 * P_crit)))
q_crit_heat_flux_MBtu = (A - xe_array[0]) / (C + ((xe_array[1:] - xe_array[0]) / q_heat_flux_MBtu))
q_crit_heat_flux = q_crit_heat_flux_MBtu * (1 / 3.41) * 1000000 * 10.7639
DNBR = q_crit_heat_flux / q_heat_flux_DNBR
plt.figure(4)
plt.plot(DNBR, z_arrayplots_DNBR)
plt.xlabel("Departure from Nucleate Boiling Ratio")
plt.ylabel("Height z [m]")
plt.savefig("DNBR.png", dpi=600)
plt.figure(5)
plt.plot(P_array, z_arrayplots)
plt.xlabel('Pressure [MPa]')
plt.ylabel('Height z [m]')
plt.savefig("Pressure.png", dpi=600)
plt.figure(6)
plt.plot(T_f_array, z_arrayplots)
plt.xlabel('Temperature [K]')
plt.ylabel('Height z [m]')
plt.savefig("TempBulk.png", dpi=600)
plt.figure(7)
plt.plot(T_F_Outer, z_arrayplots, label='Fuel Outer Surface Temp')
plt.plot(T_F_Center, z_arrayplots, label='Fuel Centerline Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempFuel.png", dpi=600)
tempdifference = T_C_Outer - T_f_array
print("Max clad vs bulk difference is " + str(np.amax(tempdifference)) + " K")
print("Max coolant temp is " + str(np.amax(T_f_array)) + " K")
print("Min coolant temp is " + str(np.amin(T_f_array)) + " K")
print("Max clad inner temp is " + str(np.amax(T_C_Inner)) + " K")
print("Max clad outer temp is " + str(np.amax(T_C_Outer)) + " K")
print("min clad outer temp is " + str(np.amin(T_C_Outer)) + " K")
print("Max fuel temp is " + str(np.amax(T_F_Center)) + " K")
print("Max fuel outer temp is " + str(np.amax(T_F_Outer)) + " K")
print("Min fuel outer temp is " + str(np.amin(T_F_Outer)) + " K")
print("Max centerline temp occurs at z = " + str(z_CL_max) + "m")
print("Max clad temp occurs at z = " + str(z_Clad_max) + "m")
MDNBR = np.amin(DNBR)
print("MDNBR is " + str(MDNBR))
plt.show()
if case == 2: # BWR
H = 3.8 # m
He = 3.8 # m
Pitch = 1.63 * 10 ** (-2) # m
Gap_t = 0.0001 # m
D_fuel = 0.0104 # m
k_gap = 0.25 # W/m-K
k_c = 21.5 # W/m-K
k_fuel = 3.6 # W/m-K
T0 = float(274 + 273.15) # K
q0_prime = float(410 * 10 ** (2)) # W/m
P0 = 7.5 # MPa
MF = float(2290) # kg/m^2-s
D_rod = .0123 # m
R_rod = D_rod / 2
R_fuel = D_fuel / 2
R_gap = R_fuel + Gap_t
R_clad = R_rod
Clad_t = D_rod - D_fuel - Gap_t # m
h0_enthalpy = (IAPWS97(T=T0, P=P0).h) * 10 ** (3)
T_sat0 = IAPWS97(P=P0, x=0).T
g = 9.81 # m/s
# geometry properties
heated_p = math.pi * D_rod
wetted_p = math.pi * D_rod
A_f = (Pitch ** 2) - ((1 / 4) * math.pi * (D_rod ** 2))
D_H = (4 * A_f) / heated_p
# grid setup
grid_points = 100
dz = H / grid_points
z_array = np.arange(0, H, dz)
z_arrayplots = np.arange(-H / 2, H / 2, dz)
q_HeatFluxList = []
# defining array of q'' values in list
for z in z_array:
heat_fluxA = (q0_prime / (math.pi * D_rod)) * math.sin(math.pi * (z / He))
q_HeatFluxList.append(heat_fluxA)
q_heat_flux = np.array(q_HeatFluxList)
q_prime = np.zeros(len(z_array))
for i in range(0, len(z_array)):
q_prime[i] = q0_prime * math.sin((np.pi * z_array[i]) / He)
# defining array of h values
h_enthalpy_list = []
h_enthalpy_prefactor = ((heated_p * q0_prime * H) / (A_f * MF * (math.pi ** 2) * D_rod))
for z in z_array:
h_enthalpy = (-h_enthalpy_prefactor * math.cos(math.pi * (z / He))) + h_enthalpy_prefactor + h0_enthalpy
h_enthalpy_list.append(h_enthalpy)
h_enthalpy_array_J = np.array(h_enthalpy_list)
h_enthalpy_array = h_enthalpy_array_J * 10 ** (-3)
P_array = np.zeros(len(z_array))
P_array[0] = P0
T_sat = np.zeros(len(z_array))
T_sat[0] = T_sat0
T_f_array = np.zeros(len(z_array))
T_f_array[0] = T0
Re = np.zeros(len(z_array))
Re_f = np.zeros(len(z_array))
Pr = np.zeros(len(z_array))
k_fluid = np.zeros(len(z_array))
x_array = np.zeros(len(z_array))
xe_array = np.zeros(len(z_array))
dxe_array = np.zeros(len(z_array))
frictional = np.zeros(len(z_array))
gravitational = np.zeros(len(z_array))
compressibility = np.zeros(len(z_array))
alpha_array = np.zeros(len(z_array))
# Pressure Loop BWR
dp = 0.001
for i in range(0, len(z_array) - 1):
rho_f = IAPWS97(P=P_array[i], x=0).rho
rho_m = IAPWS97(P=P_array[i], x=xe_array[i]).rho
vf = IAPWS97(P=P_array[i], x=0).v
vg = IAPWS97(P=P_array[i], x=1).v
vfg = vg - vf
hf_enthalpy = IAPWS97(P=P_array[i], x=0).h
hg_enthalpy = IAPWS97(P=P_array[i], x=1).h
hfg = hg_enthalpy - hf_enthalpy
hfg_sat = IAPWS97(P=P0, x=1).h - IAPWS97(P=P0, x=0).h
# vf = IAPWS97(P=P_array[i], x=0).v
# vg_sat = IAPWS97(P=P_array[i], x=1).v
hf_in = IAPWS97(P=P0, T=T0).h
muf = (IAPWS97(P=P_array[i], x=0).mu) * 10 ** (-6)
mum = (IAPWS97(P=P_array[i], x=xe_array[i]).mu) * 10 ** (-6)
mug = (IAPWS97(P=P_array[i], x=1).mu) * 10 ** (-6)
k_fluid[i] = IAPWS97(P=P_array[i], T=T_f_array[i]).k
Pr[i] = IAPWS97(P=P_array[i], h=h_enthalpy_array[i]).Liquid.Prandt
xe_in = (hf_in - hf_enthalpy) / (hfg)
vf_sat = IAPWS97(P=P_array[i], x=xe_array[i])
# vapor quality
if xe_array[i] <= 0: # single phase
Re1p = MF * D_rod / muf
f1p = 0.316 * Re1p ** (-.25)
dp = -(.5 * f1p * MF * 2 * heated_p / (rho_f * A_f) + g / rho_f) * dz
x_array[i] = 0
dxe_array[i] = q0_prime * np.sin(np.pi * z_array[i] / H) / (MF * A_f * hfg_sat) * dz
xe_array = xe_array[i - 1] + dxe_array[i]
# P_array[i]=P[i-1]+dp1p
elif xe_array[i] > 0 and xe_array[i] < 1: # 2 phase
Re2p = MF * D_rod / mum
f2p = 0.046 * Re2p ** (-.2) * (muf / mum ** (-.2))
dp2p = (-MF ** 2 * vfg * dxe_array[i] + .5 * f2p * MF ** 2 * heated_p / (rho_m * A_f) + g * rho_m) * dz
xe_array[i] = (h_enthalpy_array[i] - hf_enthalpy) / (hg_enthalpy - hf_enthalpy)
# Void Fraction
if xe_array[i] <= 0:
alpha_array[0]
elif xe_array[i] > 0 and xe_array[i] < 1:
x_array[i] = xe_array[i]
vfg_sat = vg - vf
rho_m = (vf_sat + vfg_sat * x_array) ** (-1)
rhof = 1 / vf
rhog = 1 / vg
void = (rho_m - rhof) / (rhog - rhof)
alpha_array[void]
print("Void fraction is " + str(np.amax(alpha_array)))
if xe_array[i] <= 0:
alpha_array[0]
elif xe_array[i] > 0 and xe_array[i] < 1:
x_array[i] = xe_array[i]
vfg_sat = vg - vf
rho_m = (vf_sat + vfg_sat * x_array) ** (-1)
rhof = 1 / vf
rhog = 1 / vg
void = (rho_m - rhof) / (rhog - rhof)
alpha_array[void]
print("Void fraction is " + str(np.amax(alpha_array)))
rho_m = 1 / ((x_array[i] * vg) + ((1 - x_array[i]) * vf))
mu_m = 1 / ((x_array[i] / mug) + ((1 - x_array[i]) / muf))
Re[i] = (MF * D_H) / (mu_m * 10 ** 6) # convert mu to Pa/s
f = 0.079 * (Re[i] ** -0.25) * (mu_m / muf)
Tau = (1 / 2) * f * ((MF ** 2) / rho_m)
Re_f[i] = Re[i]
vf_plus_dP = IAPWS97(P=P_array[i] + dp, x=xe_array[i]).v
vf_minus_dP = IAPWS97(P=P_array[i] - dp, x=xe_array[i]).v
ddP_vf = (vf_plus_dP - vf_minus_dP) / (2 * (dp * 10 ** 6))
frictional[i] = (Tau * wetted_p) / A_f
gravitational[i] = g * rho_f
compressibility[i] = (MF ** 2) * (ddP_vf)
dPdz_num = (frictional[i] + gravitational[i]) # Pa/m
dPdz_denom = 1 + compressibility[i] # Pa/m
dPdz = -dPdz_num / dPdz_denom # Pa/m
P_array[i + 1] = P_array[i] + ((dPdz * dz) * 10 ** (-6))
T_f_array[i + 1] = IAPWS97(P=P_array[i + 1], h=h_enthalpy_array[i + 1]).T
T_sat[i + 1] = IAPWS97(P=P_array[i + 1], x=0).T
# final calc for final value of quality and void fraction because loop stops before these
hf_final = IAPWS97(P=P_array[-1], x=0).h
hg_final = IAPWS97(P=P_array[-1], x=1).h
muf_final = (IAPWS97(P=P_array[-1], x=0).mu) * 10 ** (-6)
mug_final = (IAPWS97(P=P_array[-1], x=1).mu) * 10 ** (-6)
k_fluid[-1] = IAPWS97(P=P_array[-1], T=T_f_array[-1]).k
xe_array[-1] = (h_enthalpy_array[-1] - hf_final) / (hg_final - hf_final)
# fuel and clad temps
T_C_Outer = np.zeros(len(z_array))
mu_m_final = 1 / ((x_array[-1] / mug_final) + ((1 - x_array[-1]) / muf_final))
Re_f[-1] = (MF * D_H) / (muf_final * 10 ** 6)
Pr[-1] = IAPWS97(P=P_array[i], h=h_enthalpy_array[i]).Liquid.Prandt
h_HT = 0.023 * (Re_f[0] ** 0.8) * (Pr[0] ** 0.4) * (k_fluid[0] / D_H)
T_C_Outer[0] = (q_heat_flux[0] + (h_HT * T_f_array[0])) / h_HT
for i in range(0, len(z_array) - 1):
h_HT = 0.023 * (Re_f[i + 1] ** 0.8) * (Pr[i + 1] ** 0.4) * (k_fluid[i + 1] / D_H)
T_C_Outer[i + 1] = (q_heat_flux[i + 1] + (h_HT * T_f_array[i + 1])) / h_HT
q_triple_prime = (q_prime * 4) / (np.pi * (D_fuel ** 2))
T_C_Inner = np.zeros(len(z_array))
T_F_Outer = np.zeros(len(z_array))
T_F_Center = np.zeros(len(z_array))
for i in range(0, len(z_array)):
C1 = -((q0_prime * R_clad) / (k_c * heated_p)) * np.sin(np.pi * (z_array[i] / H))
C2 = T_C_Outer[i] - (C1 * np.log(R_clad))
T_C_Inner[i] = (C1 * np.log(R_gap)) + C2
C3 = (k_c / k_gap) * C1
C4 = T_C_Inner[i] - (C3 * np.log(R_gap))
T_F_Outer[i] = (C3 * np.log(R_fuel)) + C4
C6 = T_F_Outer[i] + ((q_triple_prime[i] * (R_fuel ** 2)) / (4 * k_fuel))
T_F_Center[i] = C6
CL_max = np.amax(T_F_Center)
index = np.where(T_F_Center == CL_max)
z_CL_max = z_array[index]
plt.figure(1)
plt.plot(T_C_Outer, z_arrayplots, label='Clad Outer Surface Temp')
plt.plot(T_C_Inner, z_arrayplots, label='Clad Inner Surface Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempCladBWR.png", dpi=600)
plt.figure(2)
plt.plot(T_C_Outer, z_arrayplots, label='Clad Outer Surface Temp')
plt.plot(T_C_Inner, z_arrayplots, label='Clad Inner Surface Temp')
plt.plot(T_F_Outer, z_arrayplots, label='Fuel Outer Surface Temp')
plt.plot(T_F_Center, z_arrayplots, label='Fuel Centerline Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempFuelAndCladBWR.png", dpi=600)
# radial calcs
T_array_A = [T_F_Center[25], T_F_Outer[25], T_C_Inner[25], T_C_Outer[25]]
T_array_B = [T_F_Center[49], T_F_Outer[49], T_C_Inner[49], T_C_Outer[49]]
T_array_C = [T_F_Center[53], T_F_Outer[53], T_C_Inner[53], T_C_Outer[53]]
r_array = [0, R_fuel, R_gap, R_clad]
plt.figure(3)
plt.plot(r_array, T_array_A, label='z = -H/4 = -0.9 m')
plt.plot(r_array, T_array_B, label='z = 0 m')
plt.plot(r_array, T_array_C, '--', label='z = zmax = 0.108 m')
plt.legend(loc='upper left')
plt.ylabel("Temperature [K]")
plt.xlabel("Radius r [m]")
plt.savefig("TempRadialBWR.png", dpi=600)
# critical heat flux and DNBR
P_array_DNBR = np.delete(P_array, 0)
q_heat_flux_DNBR = np.delete(q_heat_flux, 0)
z_arrayplots_DNBR = np.delete(z_arrayplots, 0)
G_Mlbs = MF * (((2.20462 * 10 ** (-6)) * 3600) / 10.7639)
q_heat_flux_MBtu = q_heat_flux[1:] * 3.41 * (1 / 1000000) * (1 / 10.7639)
P_c = 22.064 # https://nuclearstreet.com/nuclear-power-plants/w/nuclear_power_plants/features-of-pressurized-water-reactors
P_crit = P_array_DNBR / P_c
P1 = 0.5328
P2 = 0.1212
P3 = 1.6151
P4 = 1.4066
P5 = -0.3040
P6 = 0.4843
P7 = -0.3285
P8 = -2.0749
A = P1 * (P_crit ** P2) * (G_Mlbs ** (P5 + (P7 * P_crit)))
C = P3 * (P_crit ** P4) * (G_Mlbs ** (P6 + (P8 * P_crit)))
q_crit_heat_flux_MBtu = (A - xe_array[0]) / (C + ((xe_array[1:] - xe_array[0]) / q_heat_flux_MBtu))
q_crit_heat_flux = q_crit_heat_flux_MBtu * (1 / 3.41) * 1000000 * 10.7639
DNBR = q_crit_heat_flux / q_heat_flux_DNBR
plt.figure(4)
plt.plot(DNBR, z_arrayplots_DNBR)
plt.xlabel("Onset of Nucleate Boiling Ratio")
plt.ylabel("Height z [m]")
plt.title("Onset of Nucleate Boiling Ratio versus Height")
plt.savefig("ONBR.png", dpi=600)
plt.figure(5)
plt.plot(P_array, z_arrayplots)
plt.xlabel('Pressure [MPa]')
plt.ylabel('Height z [m]')
plt.title('Pressure versus Height')
plt.savefig("PressureBWR.png", dpi=600)
plt.figure(6)
plt.plot(T_f_array, z_arrayplots)
plt.xlabel('Temperature [K]')
plt.ylabel('Height z [m]')
plt.title('Coolant Temperature vs Height')
plt.savefig("TempBulkBWR.png", dpi=600)
plt.figure(7)
plt.plot(T_F_Outer, z_arrayplots, label='Fuel Outer Surface Temp')
plt.plot(T_F_Center, z_arrayplots, label='Fuel Centerline Temp')
plt.legend(loc='upper left')
plt.xlabel("Temperature [K]")
plt.ylabel("Height z [m]")
plt.savefig("TempFuelBWR.png", dpi=600)
# density
plt.figure(8)
plt.plot(Density, z_arrayplots, label='Density')
plt.legend(loc='upper left')
plt.xlabel("Pressure [mPa]")
plt.ylabel("Height z [m]")
plt.savefig("Density", dpi=600)
# quality
plt.figure(9)
plt.plot(x, z_arrayplots, label='Quality')
plt.plot(xe, z_arrayplots, label='Quality')
plt.legend(loc='upper left')
plt.xlabel("Quality")
plt.ylabel("Height z [m]")
plt.savefig("Quality", dpi=600)
# void
plt.figure(10)
plt.plot(alpha, z_arrayplots, label='Void Fraction')
plt.legend(loc='upper left')
plt.xlabel("Void Fraction")
plt.ylabel("Height z [m]")
plt.savefig("Void Fraction", dpi=600)
tempdifference = T_C_Outer - T_f_array
print("Max clad vs bulk difference is " + str(np.amax(tempdifference)) + " C")
print("Max coolant temp is " + str(np.amax(T_f_array) - 273.15) + " C")
print("Max coolant temp is " + str(np.amax(T_f_array)) + " K")
print("Max clad temp is " + str(np.amax(T_C_Inner) - 273.15) + " C")
print("Max clad temp is " + str(np.amax(T_C_Inner)) + " K")
print("Max fuel temp is " + str(np.amax(T_F_Center) - 273.15) + " C")
print("Max fuel temp is " + str(np.amax(T_F_Center)) + " K")
print("Max fuel temp is " + str(np.amax(T_F_Outer) - 273.15) + " C")
print("Max fuel temp is " + str(np.amax(T_F_Outer)) + " K")
print("Max centerline temp occurs at z = " + str(z_CL_max) + "m")
MDNBR = np.amin(DNBR)
print("MDNBR is " + str(MDNBR))

I'm trying to make a wage calculator but when i try to print the wages it shows zeros

I'm trying to make a wage calculator.
I'm trying to make a wage calculator but when I try to print the wages it shows zeros. I'm using Tkinter
app = Tk()
hoursWorkedWeek_text = IntVar()
hoursWorkedWeek_label = Label(app, text="Hours worked per week: ", font=("bold", 13), pady = 20)
hoursWorkedWeek_label.grid(row=0,column=0, sticky=W)
hoursWorkedWeek_entry = Entry(app, textvariable=hoursWorkedWeek_text)
hoursWorkedWeek_entry.grid(row=0,column=1)
there are 3 more like this where it gets the rate etc
_hpw = hoursWorkedWeek_entry.get()
hpw = float(_hpw)
_rph = rateEarnedPH_entry.get()
rph = float(_rph)
_oh = overtimeHours_entry.get()
oh = float(_oh)
_rot = rateForOvertime_entry.get()
rot = float(_rot)
def calculate():
_salaryPerWeek = hpw * rph + oh * rot
salaryPerWeek = str(_salaryPerWeek)
_salaryPerMonth = salaryPerWeek * 4
salaryPerMonth = str(_salaryPerMonth)
_salaryPerYear = salaryPerMonth * 12
salaryPerYear = str(_salaryPerYear)
salaryPerWeek_text = "Your Weekly Salary is " + salaryPerWeek
salaryPerMonth_text = "Your Monthly Salary is " + salaryPerMonth
salaryPerYear_text = "Your Yearly Salary is " + salaryPerYear
print(salaryPerWeek_text)
T = Text(app, height=5, width=52)
T.insert(tkinter.END, salaryPerWeek_text)
T.insert(tkinter.END, salaryPerMonth_text)
T.insert(tkinter.END, salaryPerYear_text)
and then there is the Calculate button
#Buttons
calculate_btn = Button(app, text="Calculate", width=12, command=calculate)
calculate_btn.grid(row=2,column=1, pady=20)
app.title("Salary Calculator")
app.geometry("700x400")
#Start program
app.mainloop()
Can you please explain to me what was wrong? I'm new to programming
and a rating would be nice
Thank You

run a function from a button in a frame

I'm just starting with python 3, I've made 3 scripts which do what I want them to do and now I'm trying to include them in a very basic GUI that I made with tinker.
I've joined my 3 scripts into a single file and made a function of each of them
Basically I'd like to run this or that function when I click on a button in the frame.
The problem is that of course I d'ont know how to do it, can someone point me in the right direction ?
Thanks for the help.
from tkinter import *
from datetime import *
import time
def c60duree(delta):
(h, r) = divmod(delta.seconds, 3600)
(m, s) = divmod(r, 60)
return "%s%02d:%02d:%02d" % (
"%d jour(s) " % delta.days if delta.days > 0 else "",
h,
m,
s,
)
def code60():
saisie=0
c60=[[],[]]
while saisie != "X":
c60d=datetime.now()
print ("Code 60 activé à ", c60d.strftime("%H:%M:%S"))
saisie=input("Tapez entree pour la fin du code 60, X pour sortir : ")
c60f=datetime.now()
print("Debut ", c60d.strftime("%H:%M:%S"))
print("Fin ", c60f.strftime("%H:%M:%S"))
c60x=c60f-c60d
print("Duree ", c60duree(c60x))
print("-------------")
c60[0].append(c60d)
c60[1].append(c60f)
#del(c60[0],[-1])
#del(c60[1],[-1])
#return
def relais():
rel=[[],[],[],[],[]]
print("Relais pilote demarré ")
relh=datetime.now()
relv=input("Quelle voiture ? ")
relp=input("Quel pilote repart ? ")
rele=input("Quantité d'essence ? ")
input("Tapez entrée à la sortie des stands ")
rels=datetime.now()
rel[0].append(relh), rel[1].append(relv), rel[2].append(relp), rel[3].append(rele), rel[4].append(rels)
print("Dureé ", rels-relh)
print(*rel)
def essence():
ess=[[],[],[],[]]
print("Ravitaillement essence demarré ")
essh=datetime.now()
essv=input("Quelle voiture ? ")
essp=input("Quel pilote ? ")
essq=input("Combien de litres ? ")
ess[0].append(essh), ess[1].append(essv), ess[2].append(essp), ess[3].append(essq)
print(*ess)
fenetre = Tk()
fenetre['bg']='grey'
# frame 1
Frame1 = Frame(fenetre, bg="yellow", borderwidth=1, relief=GROOVE)
Frame1.pack(side=LEFT, padx=5, pady=5)
# frame 2
Frame2 = Frame(fenetre, bg="green", borderwidth=1, relief=GROOVE)
Frame2.pack(side=LEFT, padx=5, pady=5)
# frame 3
Frame3 = Frame(fenetre, bg="red", borderwidth=1, relief=GROOVE)
Frame3.pack(side=LEFT, padx=5, pady=5)
# Ajout de labels
Label(Frame1, text="Essence").pack(padx=300, pady=100)
Label(Frame2, text="Relais").pack(padx=300, pady=100)
Label(Frame3, text="C60").pack(padx=300, pady=100)
If you want to continue using Labels, you can bind a function to them like this:
# Ajout de labels
label1 = Label(Frame1, text="Essence")
label1.bind("<Button-1>", lambda event: essence())
label1.pack(padx=300, pady=100)
label2 = Label(Frame2, text="Relais")
label2.bind("<Button-1>", lambda event: relais())
label2.pack(padx=300, pady=100)
label3 = Label(Frame3, text="C60")
label3.bind("<Button-1>", lambda event: code60())
label3.pack(padx=300, pady=100)
I've had to give the labels each a name so I could add the binding. The bind method takes a key and a function. The key I've given is Button-1, which is the left mouse button. Therefore when you click on the label the function is run. When you bind a function, and extra argument called event is added. For this example we don't need event, so I've used lambda event: to essentially ignore it and call the function like normal.
Another way you could do this is with buttons:
# Ajout de labels
Button(Frame1, text="Essence", command = essence).pack(padx=300, pady=100)
Button(Frame2, text="Relais", command = relais).pack(padx=300, pady=100)
Button(Frame3, text="C60", command = code60).pack(padx=300, pady=100)
This is a lot more straightforward but looks different to a Label.
EDIT
To make the text appear in the GUI, you could do something like this:
def essenceResult(ess, ent1, ent2, ent3):
essh=datetime.now()
essv = ent1.get()
essp = ent2.get()
essq = ent3.get()
ess[0].append(essh), ess[1].append(essv), ess[2].append(essp), ess[3].append(essq)
resultLabel = Label(Frame4, text = str(ess))
resultLabel.grid(row = 5, column = 0, columnspan = 2)
def essence():
print("yr")
Frame4.grid(row = 1, column = 0)
ess=[[],[],[],[]]
Label1 = Label(Frame4, text = "Ravitaillement essence demarré ")
Label1.grid(row = 0, column = 0, columnspan = 2)
essvLabel = Label(Frame4, text = "Quelle voiture ? ")
essvEntry = Entry(Frame4)
essvLabel.grid(row = 1, column = 0)
essvEntry.grid(row = 1, column = 1)
esspLabel = Label(Frame4, text = "Quel pilote ? ")
esspEntry = Entry(Frame4)
esspLabel.grid(row = 2, column = 0)
esspEntry.grid(row = 2, column = 1)
essqLabel = Label(Frame4, text = "Combien de litres ? ")
essqEntry = Entry(Frame4)
essqLabel.grid(row = 3, column = 0)
essqEntry.grid(row = 3, column = 1)
submitButton = Button(Frame4, text = "Submit", command = lambda: essenceResult(ess, essvEntry, esspEntry, essqEntry))
submitButton.grid(row = 4, column = 0, columnspan = 2)
fenetre = Tk()
fenetre['bg']='grey'
# frame 1
Frame1 = Frame(fenetre, bg="yellow", borderwidth=1, relief=GROOVE)
Frame1.grid(row = 0, column = 0, padx=5, pady=5)
# frame 2
Frame2 = Frame(fenetre, bg="green", borderwidth=1, relief=GROOVE)
Frame2.grid(row = 0, column = 1, padx=5, pady=5)
# frame 3
Frame3 = Frame(fenetre, bg="red", borderwidth=1, relief=GROOVE)
Frame3.grid(row = 0, column = 2, padx=5, pady=5)
Frame4 = Frame(fenetre)
Frame4 is used to show the things for essence, but is not displayed until the user presses the button. The inputs have been replaced with a label for the question and an entry for the user to put their answer. Then when they press submit, the essenceResult function adds a label with what the print function used to show.

I am trying to display my outputs in the entry box widgets but nothing is showing upon execution yet no error

I think I am having a challenge in importing the monthlyPayment and the totalPayment value from the ComputePayment function. So I want to input value in:
loanAmount entry box
annual interest rate entry box
number of years interest box
such dat when I press the COMPUTE PAYMENT BUTTON the answers are displayed in the entry of monthly payments and total payments. Looking forwards to your assistance thank you.
Below is the code and a picture of what I am trying to run, its a loan calculator:
from tkinter import *
from PIL import ImageTk, Image
import db
from tkinter import messagebox
import show_client
class LoanCalculator:
def __init__(self, data = ''):
self.data = data
print(self.data)
self.win = Tk()
#Reset The Window & Background Color
canvas = Canvas(self.win, width=250, height=550, bg = "black")
canvas.pack(expand=YES, fill=BOTH)
#Show Window In The Center Of The Screen
width = self.win.winfo_screenwidth()
height = self.win.winfo_screenheight()
x = int(width / 2 - 475 / 2)
y = int(height / 2 - 400 / 2)
str1 = "475x400+"+str(x)+"+"+ str(y)
self.win.geometry(str1)
self.win.resizable(width=False, height=False)
#Change Icon
self.win.iconbitmap("titico.ico")
self.win.title("LOAN CALCULATOR | AJULES BACAS 1.0")
#Change Icon
self.win.iconbitmap("titico.ico")
def add_frame(self):
self.frame = Frame(self.win, height=375, width=450)
self.frame.place(x = 12.5,y=12.5)
x, y = 70, 20
self.label = Label(self.frame, text="Please Enter The Loan Details Below:")
self.label.config(font=('Ebrima', 14, 'bold'))
self.label.place(x = 60, y = y + 55)
#Enter Loan Interest Rate
self.ir = Label(self.frame, text='Loan Annual Interest Rate')
self.ir.config(font=('Ebrima', 12))
self.ir.place(x = 5, y = 120)
self.ir = Entry(self.frame, font='Ebrima 12', highlightbackground = "gold", highlightthickness = 1)
self.ir.place(x=250, y = 120)
#Enter Number of Years
self.noy = Label(self.frame, text='Number of Years')
self.noy.config(font=('Ebrima', 12))
self.noy.place(x=5, y = 150)
self.noy = Entry(self.frame, font='Ebrima 12', highlightbackground = "gold", highlightthickness = 1)
self.noy.place(x=250, y = 150)
#Enter Loan Amount
self.ln = Label(self.frame, text='Loan Amount')
self.ln.config(font=('Ebrima', 12))
self.ln.place(x=5, y = 180)
self.ln = Entry(self.frame, font='Ebrima 12', highlightbackground = "gold", highlightthickness = 1)
self.ln.place(x=250, y = 180)
#Monthly Payment
self.monthlyPayment = Label(self.frame, text='The Monthly Payment Is:')
self.monthlyPayment.config(font=('Ebrima', 12, 'bold'))
self.monthlyPayment.place(x=5, y = 290)
self.monthlyPaymentVar = StringVar()
self.monthlyPayment = Entry(self.frame, font='Ebrima 12', textvariable = self.monthlyPaymentVar, highlightbackground = "gold", highlightthickness = 1)
self.monthlyPayment.place(x=250, y = 290)
#Total Payment
self.totalPayment = Label(self.frame, text='The Total Payment Is:')
self.totalPayment.config(font=('Ebrima', 12, 'bold'))
self.totalPayment.place(x=5, y = 330)
self.totalPaymentVar = StringVar()
self.totalPayment = Entry(self.frame, font='Ebrima 12', textvariable=self.totalPaymentVar, highlightbackground = "gold", highlightthickness = 1)
self.totalPayment.place(x=250, y = 330)
self.button = Button(self.frame, text='COMPUTE PAYMENT', font='Ebrima 14 bold', fg = "gold", bg = "black", command=self.ComputePayment)
self.button.place(x = 75, y = 230, width = 300, height = 40)
return
def ComputePayment(self):
self.ir.get()
self.noy.get()
self.ln.get()
ir = float(self.ir.get())
noy = eval(self.noy.get())
ln = float(self.ln.get())
monthlyInterestRate = ir / 1200
monthlyPayment = ln * monthlyInterestRate / (1 - 1 / (1 + monthlyInterestRate) ** (noy * 12))
print(monthlyPayment)
self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
totalPayment = monthlyPayment * 12 * noy
self.totalPaymentVar.set(format(totalPayment, '10.2f'))
print(totalPayment)
return
enter image description here
I think that you didn't call the add_frame method so that will be the mistake
and i don't know why you have imported pillow ,db, showclient,messagebox. Even without it, it still run.
from tkinter import *
from PIL import ImageTk, Image
import db
from tkinter import messagebox
import show_client
class LoanCalculator:
def __init__(self, data = ''):
self.data = data
print(self.data)
self.win = Tk()
#Reset The Window & Background Color
canvas = Canvas(self.win, width=250, height=550, bg = "black")
canvas.pack(expand=YES, fill=BOTH)
#Show Window In The Center Of The Screen
width = self.win.winfo_screenwidth()
height = self.win.winfo_screenheight()
x = int(width / 2 - 475 / 2)
y = int(height / 2 - 400 / 2)
str1 = "475x400+"+str(x)+"+"+ str(y)
self.win.geometry(str1)
self.win.resizable(width=False, height=False)
#Change Icon
self.win.iconbitmap("titico.ico")
self.add_frame()
self.win.title("LOAN CALCULATOR | AJULES BACAS 1.0")
#Change Icon
self.win.iconbitmap("titico.ico")
def add_frame(self):
self.frame = Frame(self.win, height=375, width=450)
self.frame.place(x = 12.5,y=12.5)
x, y = 70, 20
self.label = Label(self.frame, text="Please Enter The Loan Details Below:")
self.label.config(font=('Ebrima', 14, 'bold'))
self.label.place(x = 60, y = y + 55)
#Enter Loan Interest Rate
self.ir = Label(self.frame, text='Loan Annual Interest Rate')
self.ir.config(font=('Ebrima', 12))
self.ir.place(x = 5, y = 120)
self.ir = Entry(self.frame, font='Ebrima 12', highlightbackground = "gold", highlightthickness = 1)
self.ir.place(x=250, y = 120)
#Enter Number of Years
self.noy = Label(self.frame, text='Number of Years')
self.noy.config(font=('Ebrima', 12))
self.noy.place(x=5, y = 150)
self.noy = Entry(self.frame, font='Ebrima 12', highlightbackground = "gold", highlightthickness = 1)
self.noy.place(x=250, y = 150)
#Enter Loan Amount
self.ln = Label(self.frame, text='Loan Amount')
self.ln.config(font=('Ebrima', 12))
self.ln.place(x=5, y = 180)
self.ln = Entry(self.frame, font='Ebrima 12', highlightbackground = "gold", highlightthickness = 1)
self.ln.place(x=250, y = 180)
#Monthly Payment
self.monthlyPayment = Label(self.frame, text='The Monthly Payment Is:')
self.monthlyPayment.config(font=('Ebrima', 12, 'bold'))
self.monthlyPayment.place(x=5, y = 290)
self.monthlyPaymentVar = StringVar()
self.monthlyPayment = Entry(self.frame, font='Ebrima 12', textvariable = self.monthlyPaymentVar, highlightbackground = "gold", highlightthickness = 1)
self.monthlyPayment.place(x=250, y = 290)
#Total Payment
self.totalPayment = Label(self.frame, text='The Total Payment Is:')
self.totalPayment.config(font=('Ebrima', 12, 'bold'))
self.totalPayment.place(x=5, y = 330)
self.totalPaymentVar = StringVar()
self.totalPayment = Entry(self.frame, font='Ebrima 12', textvariable=self.totalPaymentVar, highlightbackground = "gold", highlightthickness = 1)
self.totalPayment.place(x=250, y = 330)
self.button = Button(self.frame, text='COMPUTE PAYMENT', font='Ebrima 14 bold', fg = "gold", bg = "black", command=self.ComputePayment)
self.button.place(x = 75, y = 230, width = 300, height = 40)
return
def ComputePayment(self):
self.ir.get()
self.noy.get()
self.ln.get()
ir = float(self.ir.get())
noy = eval(self.noy.get())
ln = float(self.ln.get())
monthlyInterestRate = ir / 1200
monthlyPayment = ln * monthlyInterestRate / (1 - 1 / (1 + monthlyInterestRate) ** (noy * 12))
print(monthlyPayment)
self.monthlyPaymentVar.set(format(monthlyPayment, '10.2f'))
totalPayment = monthlyPayment * 12 * noy
self.totalPaymentVar.set(format(totalPayment, '10.2f'))
print(totalPayment)
return
LoanCalculator()

My code wont run properly when other files try to use it

So my code as been acting up and I don't know what the problem is. When I try to test the file "Battle" it works like it supposed to and everything is fine. It pulls up a tkinter window like I want to, shows the buttons, My sprites, etc. But when I use my main file to run the Battle file it doesn't show the buttons, listbox, or sprites. I looked all over my code and I cant find out whats wrong. If anyone could help me then that would be great! It's a lot of code and I am kinda a rookie so it may not be the cleanest but I do leave a lot of notes.
This is the Battle code:
import tkinter as tk
import random
import time
inBattle = False
gameOver = True
i = 0
enemy_type = 0
MAX_HP = 60
MAX_MP = 40
HPval = 20
MPval = 30
POTIONSval = 3
#test
def add_text(recap):
global i
recap.insert(0, 'Damage: ' + str(i))
i += 1
#switch to turn the whole thing on or off
def GameOver():
global gameOver
if gameOver == True:
gameOver = False
else:
gameOver = True
#spells
def Cast_Fireball(spells, MP, recap):
global MPval
if MPval - 10 > 0 or MPval - 10 == 0:
MPval -= 10
MP.config(text='MP: ' + str(MPval))
hit = random.randint(0, 100)
damage = random.randint(1,10) # 1d10
if hit > 9: # 90%
recap.insert(0, 'Hit for ' + str(damage))
spells.destroy()
else:
recap.insert(0, 'Missed!')
spells.destroy()
else:
recap.insert(0, 'Not enough mana.')
spells.destroy()
def Cast_Iceball(spells, MP, recap):
global MPval
if MPval - 12 > 0 or MPval - 12 == 0:
MPval -= 12
MP.config(text='MP: ' + str(MPval))
hit = random.randint(0, 100)
damage = random.randint(1,6) * 2 # 2d6
if hit > 4: # 95%
recap.insert(0, 'Hit for ' + str(damage))
spells.destroy()
else:
recap.insert(0, 'Missed!')
spells.destroy()
else:
recap.insert(0, 'Not enough mana.')
spells.destroy()
def Cast_Heal(spells, HP, MP, recap):
global MPval
global HPval
if MPval - 15 > 0 or MPval - 15 == 0:
if HPval < MAX_HP:
MPval -= 15
MP.config(text='MP: ' + str(MPval))
damage = random.randint(7,25) # 2d10 + 5
if HPval + damage > MAX_HP:
damage = MAX_HP - HPval
recap.insert(0, 'Healed for ' + str(damage))
HPval += damage
HP.config(text='HP: ' + str(HPval))
spells.destroy()
else:
recap.insert(0, 'Not enough mana.')
spells.destroy()
def Cast_Drain(spells, MP, recap):
global MPval
hit = random.randint(0, 100)
damage = random.randint(1,6) # 1d6
if hit > 19: # 80%
recap.insert(0, 'Hit for ' + str(damage))
recap.insert(0, 'Recovered some mana!')
MPval += damage
MP.config(text='MP: ' + str(MPval))
spells.destroy()
else:
recap.insert(0, 'Missed!')
spells.destroy()
#activates window for spell list
def Spell_list(HP, MP, recap):
spells = tk.Tk()
spells.title("Spell List")
spells.minsize(150,168)
Fireball = tk.Button(spells, text='Fireball', bg='black', font=("arial", 15, "bold"), fg="white", width=12, command= lambda: Cast_Fireball(spells, MP, recap))
Fireball.pack()
Iceball = tk.Button(spells, text='Iceball', bg='black', font=("arial", 15, "bold"), fg="white", width=12, command= lambda: Cast_Iceball(spells, MP, recap))
Iceball.pack()
Mana_Drain = tk.Button(spells, text='Mana Drain', bg='black', font=("arial", 15, "bold"), fg="white", width=12, command= lambda: Cast_Drain(spells, MP, recap))
Mana_Drain.pack()
Crude_Heal = tk.Button(spells, text='Crude Heal', bg='black', font=("arial", 15, "bold"), fg="white", width=12, command= lambda: Cast_Heal(spells, HP, MP, recap))
Crude_Heal.pack()
spells.mainloop()
#drinks a max hp potion and checks if your full already and doesn't use it
def Drink_Potion(HP,POTIONS,recap):
global HPval
global POTIONSval
if POTIONSval > 0 and HPval < MAX_HP:
temp = MAX_HP - HPval
HPval = MAX_HP
POTIONSval -= 1
recap.insert(0, 'Healed for ' + str(temp))
HP.config(text="HP: " + str(HPval))
POTIONS.config(text="Potions: " + str(POTIONSval))
#main fucntion
def Battle():
#trigger so the player on the other screen is stopped and cant move
global inBattle
global HPval
global MPval
global POTIONSval
global enemy_type
inBattle = True
#screen settings
screen = tk.Tk()
screen.title("Encounter")
screen.minsize(1000,500)
screen.configure(bg='black')
#background settings and rectangle for the bottom half of screen
canvas = tk.Canvas(screen, width=1000, height=500)
canvas.configure(bg='black')
canvas.pack()
canvas.create_rectangle(3,300,1000,500,fill='white')
sprites = tk.Canvas(screen, width=200, height=200, bg='black')
sprites.place(x=285, y=50)
#choses which enemy to fight
#enemy_type = random.randint(0,6)
#spawning of the enemy
if enemy_type == 0:
img = tk.PhotoImage(file='sprites/slime.png')
sprites.create_image(20,20, image=img, anchor="nw")
#box on right to list the past actions
recap = tk.Listbox(screen, font=("arial", 14), bg="white", width=22, height=12)
recap.place(x=754, y=10)
#trackers for health, mana, and potions
HP = tk.Label(screen, text="HP: " + str(HPval), font=("arial",30), bg="white")
HP.place(x=775, y=310)
MP = tk.Label(screen, text="MP: " + str(MPval), font=("arial",30), bg="white")
MP.place(x=775, y=360)
Potions = tk.Label(screen, text="Potions: " + str(POTIONSval), font=("arial",30), bg="white")
Potions.place(x=775, y=410)
#buttons for commands
Attack = tk.Button(screen,text="Attack",width=9, height=4, bg="black", fg="white", font=("arial", 24, "bold"), command= lambda: add_text(recap))
Attack.place(x=10, y= 313)
Defend = tk.Button(screen,text="Defend",width=9, height=4, bg="black", fg="white", font=("arial", 24, "bold"))
Defend.place(x=200, y= 313)
Item = tk.Button(screen,text="Item",width=9, height=4, bg="black", fg="white", font=("arial", 24, "bold"), command= lambda: Drink_Potion(HP, Potions, recap))
Item.place(x=390, y= 313)
Magic = tk.Button(screen,text="Magic",width=9, height=4, bg="black", fg="white", font=("arial", 24, "bold"), command= lambda: Spell_list(HP, MP, recap))
Magic.place(x=580, y= 313)
screen.mainloop()
#testing purposes / comment out on release
#Battle()
This is the Main code:
import random
import turtle
import tkinter as tk
import time
import Battle
callOnce = False
GWIDTH = 800
GHEIGHT = 800
SWIDTH = 50
SHEIGHT = 50
START_Y = 0
END_Y = 0
PLAYER_X = 0
PLAYER_Y = 0
BUFFER = 80
DungeonCord = []
DungeonStorage = []
Treasure = []
pathingPlaces = []
pathingAmount = 0
start = tk.Tk()
start.title("Dungeon Generator")
start.minsize(500,500)
#generate function making it save the set x and y and passing it to the turtle functions
def Generate():
global GHEIGHT
global GWIDTH
Battle.GameOver()
GWIDTH = xInsert.get()
GHEIGHT = yInsert.get()
start.destroy()
DunGenText = tk.Label(text="Dungeon Generator", relief="solid", width = 20, font=("arial", 24, "bold"))
DunGenText.place(x=60, y=35)
xLabel = tk.Label(text="X Grid Count:", width = 10, font=("arial", 14))
xLabel.place(x=145,y=145)
xInsert = tk.Entry(start, width=5)
xInsert.place(x=280,y=150)
yLabel = tk.Label(text="Y Grid Count:", width = 10, font=("arial", 14))
yLabel.place(x=145,y=245)
yInsert = tk.Entry(start, width=5)
yInsert.place(x=280,y=250)
button = tk.Button(start,text="Generate",width=30, bg="black", fg="white", command=Generate)
button.place(x=135, y=450)
start.mainloop()
#main loop for the turtle side of things
while not Battle.gameOver:
#window settings
wn = turtle.Screen()
wn.title("Dungeon Crawler")
wn.setup(width=(int(GWIDTH) * int(SWIDTH))+BUFFER, height=(int(GHEIGHT) * int(SHEIGHT))+BUFFER)
wn.bgcolor("black")
wn.tracer(0)
#where the grid would start to draw itself
Gridx = (int(GWIDTH) * int(SWIDTH) * -1) / 2
Gridy = (int(GHEIGHT) * int(SHEIGHT)) /2
#this will determine the lowest number between the x axis and the y axis
if int(GWIDTH) > int(GHEIGHT):
LOWEST = int(GHEIGHT)
else:
LOWEST = int(GWIDTH)
#this is the formula for the dungeon count in the grid // ((x * y) - 2y) / l
DCOUNT = ((int(GHEIGHT) * int(GWIDTH)) - (2 * int(GHEIGHT))) / int(LOWEST)
#the function to draw the grid
def draw_grid(t, x, y, sx, sy,):
for i in range(int(y)):
for j in range(int(x)):
t.penup()
t.goto(x= Gridx + (sx * int(j)), y= Gridy - (sy * int(i)))
t.pendown()
t.forward(sx)
t.right(90)
t.forward(sx)
t.right(90)
t.forward(sx)
t.right(90)
t.forward(sx)
t.right(90)
#function to draw a square at a location
def draw_square(t, s):
for i in range(4):
t.forward(int(s) * 20)
t.right(90)
#drawing the circle on the left side that would be the start
def draw_start(t, t2):
global START_Y
global PLAYER_Y
START_Y = random.randint(0, int(GHEIGHT) - 1)
PLAYER_Y = START_Y
t.penup()
t.goto(x= Gridx + (SWIDTH / 2), y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * START_Y) - 10)
t.pendown()
t.circle(10)
t2.penup()
t2.goto(x= Gridx + (SWIDTH / 2), y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * START_Y))
t2.pendown()
draw_player(t2)
#drawing a circle on the right side that would be the end
def draw_end(t):
global END_Y
END_Y = random.randint(0, int(GHEIGHT) - 1)
t.penup()
t.goto(x= (Gridx + (SWIDTH / 2)) * -1, y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * END_Y) - 10)
t.pendown()
t.circle(10)
#draws the player at its location
def draw_player(t):
t.penup()
t.goto(x= (Gridx + (SWIDTH / 2)) + (SWIDTH * PLAYER_X) - 10, y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * PLAYER_Y)+3)
t.pendown()
for i in range(50):
t.forward(20)
t.right(144)
#drawing the dungeon at random locations that can be anyware between the entrance and the exit.
def draw_dungeons(t, d):
global DungeonCord
global Treasure
for i in range(int(d)):
closestX = random.randint(1, int(GWIDTH) - 2)
closestY = random.randint(0, int(GHEIGHT) - 1)
DungeonCord.append((closestX,closestY))
DungeonStorage.append((closestX,closestY))
for j in range(i):
if DungeonCord[j] == DungeonCord[i]:
closestX = random.randint(1, int(GWIDTH) - 2)
closestY = random.randint(0, int(GHEIGHT) - 1)
DungeonCord[i] = (closestX,closestY)
DungeonStorage[i] = (closestX,closestY)
if DungeonCord[j] == DungeonCord[i]:
closestX = random.randint(1, int(GWIDTH) - 2)
closestY = random.randint(0, int(GHEIGHT) - 1)
DungeonCord[i] = (closestX,closestY)
DungeonStorage[i] = (closestX,closestY)
#treasure room chance
TR = random.randint(1,5)
if TR == 5:
t.color("yellow")
Treasure.append(DungeonCord[i])
t.penup()
t.goto(x= (Gridx + (SWIDTH / 2)) + (SWIDTH * closestX) - 10, y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * closestY) + 10)
t.pendown()
draw_square(t, 1)
t.color("white")
#the pathmaking function that would go to each dungeon and from the start to the end
def draw_path(t):
global DungeonCord
global START_Y
global END_Y
global DCOUNT
global pathingAmount
global pathingPlaces
t.penup()
t.goto(x= Gridx + (SWIDTH / 2), y= (Gridy - (SHEIGHT / 2)) - (SHEIGHT * START_Y))
t.pendown()
myCordsx = 0
myCordsy = START_Y
dungeon = 0
for j in range(int(DCOUNT)):
traveling = True
closestX = 500
closestY = 500
#finds the closest dungeon
for i in range(int(DCOUNT)):
x, y = DungeonCord[i]
if abs(x - myCordsx) + abs(y - myCordsy) < abs(closestX - myCordsx) + abs(closestY - myCordsy):
closestX, closestY = x, y
dungeon = i
elif abs(x - myCordsx) + abs(y - myCordsy) == abs(closestX - myCordsx) + abs(closestY - myCordsy):
if x < closestX:
closestX, closestY = x, y
dungeon = i
#path to the current closest dungeon
while traveling:
if closestX > myCordsx: #path right
t.forward(int(SWIDTH))
myCordsx += 1
pathingPlaces.append((myCordsx, myCordsy))
pathingAmount +=1
elif closestY > myCordsy: #path down
t.right(90)
t.forward(int(SWIDTH))
t.left(90)
myCordsy += 1
pathingPlaces.append((myCordsx, myCordsy))
pathingAmount +=1
elif closestX < myCordsx: #path left
t.right(180)
t.forward(int(SWIDTH))
t.left(180)
myCordsx -= 1
pathingPlaces.append((myCordsx, myCordsy))
pathingAmount +=1
elif closestY < myCordsy: #path up
t.left(90)
t.forward(int(SWIDTH))
t.right(90)
myCordsy -= 1
pathingPlaces.append((myCordsx, myCordsy))
pathingAmount +=1
else:
traveling = False
i = 0 #reset on counter
DungeonCord[dungeon] = (99, 99) #null entry / dungeon is checked off
#pathing to the end
traveling = True
while traveling:
if int(GWIDTH) - 1 > myCordsx: #going right
t.forward(int(SWIDTH))
myCordsx += 1
pathingPlaces.append((myCordsx, myCordsy))
pathingAmount +=1
elif END_Y > myCordsy: #going down
t.right(90)
t.forward(int(SWIDTH))
t.left(90)
myCordsy += 1
pathingPlaces.append((myCordsx, myCordsy))
pathingAmount +=1
elif int(GWIDTH) - 1 != myCordsx and END_Y == myCordsy: #going left
t.right(180)
t.forward(int(SWIDTH))
t.left(180)
myCordsx -= 1
pathingPlaces.append((myCordsx, myCordsy))
pathingAmount +=1
elif int(GWIDTH) - 1 == myCordsx and END_Y != myCordsy: #going up
t.left(90)
t.forward(int(SWIDTH))
t.right(90)
myCordsy -= 1
pathingPlaces.append((myCordsx, myCordsy))
pathingAmount +=1
else:
traveling = False
#all the turtle units involved in drawing
grid = turtle.Turtle()
grid.hideturtle()
grid.pencolor("white")
entrance = turtle.Turtle()
entrance.hideturtle()
entrance.pencolor("green")
end = turtle.Turtle()
end.hideturtle()
end.pencolor("red")
dun = turtle.Turtle()
dun.hideturtle()
dun.pencolor("white")
dun.shape("square")
path = turtle.Turtle()
path.hideturtle()
path.pencolor("green")
player = turtle.Turtle()
player.hideturtle()
player.pencolor("pink")
#player movement
def moveUP():
global PLAYER_X
global PLAYER_Y
for i in range(pathingAmount):
if (PLAYER_X, PLAYER_Y - 1) == pathingPlaces[i] and not Battle.inBattle:
PLAYER_Y -= 1
player.clear()
draw_player(player)
for i in range(int(DCOUNT)):
if (PLAYER_X, PLAYER_Y) == DungeonStorage[i]:
Battle.Battle()
break
def moveDOWN():
global PLAYER_X
global PLAYER_Y
for i in range(pathingAmount):
if (PLAYER_X, PLAYER_Y + 1) == pathingPlaces[i] and not Battle.inBattle:
PLAYER_Y += 1
player.clear()
draw_player(player)
for i in range(int(DCOUNT)):
if (PLAYER_X, PLAYER_Y) == DungeonStorage[i]:
Battle.Battle()
break
def moveLEFT():
global PLAYER_X
global PLAYER_Y
for i in range(pathingAmount):
if (PLAYER_X - 1, PLAYER_Y) == pathingPlaces[i] and not Battle.inBattle:
PLAYER_X -= 1
player.clear()
draw_player(player)
for i in range(int(DCOUNT)):
if (PLAYER_X, PLAYER_Y) == DungeonStorage[i]:
Battle.Battle()
break
def moveRIGHT():
global PLAYER_X
global PLAYER_Y
for i in range(pathingAmount):
if (PLAYER_X + 1, PLAYER_Y) == pathingPlaces[i] and not Battle.inBattle:
PLAYER_X += 1
player.clear()
draw_player(player)
for i in range(int(DCOUNT)):
if (PLAYER_X, PLAYER_Y) == DungeonStorage[i]:
Battle.Battle()
break
#a call once function so the dungeons, start, and end doesn't keep drawing.
if callOnce == False:
draw_grid(grid, GWIDTH, GHEIGHT, SWIDTH, SHEIGHT)
draw_start(entrance, player)
draw_end(end)
draw_dungeons(dun, DCOUNT)
draw_path(path)
callOnce = True
wn.listen()
wn.onkey(moveRIGHT, "d")
wn.onkey(moveUP, "w")
wn.onkey(moveLEFT, "a")
wn.onkey(moveDOWN, "s")
while True:
wn.update()
Never Mind, the problem was tkinter itself. Just needed to change the tk.Tk() in my battle code to tk.Toplevel() since you cant have two tk.Tk() code. Well..... Damn

Resources