Tkinter error type variable [duplicate] - python

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 6 years ago.
I am an electrical engineer and I am new to Python programming.
I want to write a Python program for three phase transformer calculator. The program is very simple, it does just a few algebraic operation; I wrote simple python code without GUI and it worked very fine. So I decided to make the same program using Tkinter module to give a GUI to my application. I had some error and I read a lot of questions and asked many questions on this community, but I am not able to solve it. I am not able to trace the cause of the error. The code is:
from tkinter import *
from math import *
finestra=Tk()
finestra.geometry('800x800+300+300')
finestra.title('Dimensionamento Trasformatore')
def calcola(Vn,Vn2,Sn,Vcc,V_spira,f,Bmax,mu,J,w,Snf,N1,N2,If1,If2,kv,ki,fi,fi_c,S_colonna,S_conduttore1,S_conduttore2,Sezione_netta_cu1,Sezione_netta_cu2,Vf1,Vf2):
try:
#lettura caselle di testo/ read entry
Vn=float(Vn_s.get())
Vn2=float(Vn2_s.get())
Vcc=float(Vcc_s.get())
V_spira=float(Vspira_s.get())
Sn=float(Sn_s.get())
J=float(J_s.get())
mu=float(mu_s.get())
Bmax=float(Bmax_s.get())
f=float(f_s.get())
except ValueError:
print('inserito valore sbagliato')
else:
#calcoli / calculate
if (var_1.get()==1):
collegamento1='triangolo'
else:
collegamento1='stella'
if (var_2.get()==1):
collegamento2='triangolo'
else:
collegamento2='stella'
Snf=(Sn/3.0)
w=(2*pi*f)
if (collegamento1=='triangolo'):
Vf1=Vn
else:
Vf1=(Vn/sqrt(3))
if (collegamento2=='triangolo'):
Vf2=(Vn2)
else:
Vf2=(Vn2/sqrt(3))
N1=Vf1/V_spira
N2=Vf2/V_spira
If1=Snf/Vf1
If2=(Snf/Vf2)
kv=Vf1/Vf2
ki=If2/If1
fi=Vf1/(w*N1)
fi_c=(N1*fi)
S_colonna=(fi_c/(Bmax*sqrt(2)))
S_conduttore1=(If1/J)
S_conduttore2=(If2/J)
# Sezione_netta_cu1.set(S_conduttore1*N1/k_stip_cu)
# Sezione_netta_cu2.set(S_conduttore2*N2/k_stip_cu)
testo_23=Label(finestra,text=str(N1)).grid(sticky=W,row=4,column=5)
testo_24=Label(finestra,text=str(N2)).grid(sticky=W,row=6,column=5)
testo_25=Label(finestra,text=str(kv)).grid(sticky=W,row=11,column=5)
testo_26=Label(finestra,text=str(ki)).grid(sticky=W,row=13,column=5)
testo_27=Label(finestra,text=str(fi_c)).grid(sticky=W,row=21,column=5)
testo_28=Label(finestra,text=str(S_colonna)).grid(sticky=W,row=25,column=5)
testo_29=Label(finestra,text=str(S_conduttore1)).grid(sticky=W,row=19,column=5)
testo_30=Label(finestra,text=str(S_conduttore2)).grid(sticky=W,row=17,column=5)
## testo_31=Label(finestra,text=str(Sezione_netta_cu1)).grid(sticky=W,row=16,column=5)
## testo_32=Label(finestra,text=str(Sezione_netta_cu2)).grid(sticky=W,row=8,column=5)
## testo_33=Label(finestra,text=str(N1)).grid(sticky=W,row=14,column=5)
## testo_34=Label(finestra,text=str(N1)).grid(sticky=W,row=22,column=5)
return;
#Testi / label
testo_0=Label(finestra,text="Parametri di ingresso:").grid(sticky=W,row=0,column=0)
testo_1=Label(finestra,text="Collegamento primario:").grid(sticky=W,row=3,column=0)
testo_2=Label(finestra,text="Collegamento secondario:").grid(sticky=W,row=5,column=0)
testo_3=Label(finestra,text="Tensione nominale concatenata primaria:").grid(sticky=W,row=10,column=0)
testo_4=Label(finestra,text="Tensione nominale concatenata secondaria:").grid(sticky=W,row=12,column=0)
testo_5=Label(finestra,text="Induzione massima:").grid(sticky=W,row=20,column=0)
testo_6=Label(finestra,text="Densita di corrente:").grid(sticky=W,row=24,column=0)
testo_7=Label(finestra,text="Frequenza:").grid(sticky=W,row=18,column=0)
testo_8=Label(finestra,text="Tensione di corto circuito:").grid(sticky=W,row=16,column=0)
testo_9=Label(finestra,text="Potenza apparente nominale:").grid(sticky=W,row=8,column=0)
testo_10=Label(finestra,text="Volt-spira:").grid(sticky=W,row=14,column=0)
testo_11=Label(finestra,text="Permeabilita del ferro:").grid(sticky=W,row=22,column=0)
testo_12=Label(finestra,text="Valori calcolati:").grid(sticky=W,row=0,column=5)
testo_13=Label(finestra,text="Numero spire primario:").grid(sticky=W,row=3,column=5)
testo_14=Label(finestra,text="Numero spire secondario:").grid(sticky=W,row=5,column=5)
testo_15=Label(finestra,text="Rapporto trasformazione tensione:").grid(sticky=W,row=10,column=5)
testo_16=Label(finestra,text="Rapporto trasformazione corrente:").grid(sticky=W,row=12,column=5)
testo_17=Label(finestra,text="Flusso concatenato efficace:").grid(sticky=W,row=20,column=5)
testo_18=Label(finestra,text="Sezione colonna:").grid(sticky=W,row=24,column=5)
testo_19=Label(finestra,text="Sezione conduttore primario:").grid(sticky=W,row=18,column=5)
testo_20=Label(finestra,text="Sezione conduttore secondario:").grid(sticky=W,row=16,column=5)
testo_21=Label(finestra,text="Sezione avvolgimento primario netta:").grid(sticky=W,row=8,column=5)
testo_22=Label(finestra,text="Sezione avvolgimento secondario netta:").grid(sticky=W,row=14,column=5)
#variabili
If1=DoubleVar()
If2=DoubleVar()
N1=DoubleVar()
N2=DoubleVar()
var_1=IntVar()
var_2=IntVar()
Vn=DoubleVar()
Vf1=DoubleVar()
Vf2=DoubleVar()
Vn2=DoubleVar()
Vcc=DoubleVar()
V_spira=DoubleVar()
Sn=DoubleVar()
Snf=DoubleVar()
J=DoubleVar()
mu=DoubleVar()
Bmax=DoubleVar()
f=DoubleVar()
Vn_s=StringVar()
Vn2_s=StringVar()
Vcc_s=StringVar()
Vspira_s=StringVar()
Sn_s=StringVar()
J_s=StringVar()
mu_s=StringVar()
Bmax_s=StringVar()
f_s=StringVar()
collegamento1=StringVar()
collegamento2=StringVar()
w=DoubleVar()
kv=DoubleVar()
ki=DoubleVar()
fi=DoubleVar()
fi_c=DoubleVar()
S_colonna=DoubleVar()
S_conduttore1=DoubleVar()
S_conduttore2=DoubleVar()
Sezione_netta_cu1=DoubleVar()
Sezione_netta_cu2=DoubleVar()
#Radiobutton
#collegamento primario/ first winding
collegamentoI_1=Radiobutton(finestra,text='triangolo',value=1,variable=var_1)
collegamentoI_1.grid(row=4,column=0)
collegamentoI_2=Radiobutton(finestra,text='stella',value=2,variable=var_1)
collegamentoI_2.grid(row=4,column=1)
#collegamento secondario/ second winding
collegamentoII_1=Radiobutton(finestra,text='triangolo',value=1,variable=var_2)
collegamentoII_1.grid(row=6,column=0)
collegamentoII_2=Radiobutton(finestra,text='stella',value=2,variable=var_2)
collegamentoII_2.grid(row=6,column=1)
#caselle di testo / entry
Vn_=Entry(finestra,textvariable=Vn_s)
Vn_.grid(row=11,column=0)
Vspira_=Entry(finestra,textvariable=Vspira_s)
Vspira_.grid(row=15,column=0)
Vn2_=Entry(finestra,textvariable=Vn2_s)
Vn2_.grid(row=13,column=0)
Sn_=Entry(finestra,textvariable=Sn_s)
Sn_.grid(row=9,column=0)
Bmax_=Entry(finestra,textvariable=Bmax_s)
Bmax_.grid(row=21,column=0)
mu_=Entry(finestra,textvariable=mu_s)
mu_.grid(row=23,column=0)
Vcc_=Entry(finestra,textvariable=Vcc_s)
Vcc_.grid(row=17,column=0)
f_=Entry(finestra,textvariable=f_s)
f_.grid(row=19,column=0)
J_=Entry(finestra,textvariable=J_s)
J_.grid(row=25,column=0)
#Calculatebutton
gobutton=Button(finestra,text='Calcola',command=calcola(Vn,Vn2,Sn,Vcc,V_spira,f,Bmax,mu,J,w,Snf,N1,N2,If1,If2,kv,ki,fi,fi_c,S_colonna,S_conduttore1,S_conduttore2,Sezione_netta_cu1,Sezione_netta_cu2,Vf1,Vf2))
gobutton.grid(row=28, column=3)
finestra.mainloop()
The first kind of error I had was a ValueError: could not convert string to float. I read this could happen because at the start time, the entry widgets are empty so python can convert it to float. So I added try/except block. Now when I start the program, it prints an error message in except block (I can't understand this: the calcola function is associated to the calculate button, but it seems to run the function without button press, at start time) then don't happen anything else, though writing number in entry box and pressing calculate button. What I suspect is that the way I am using function is wrong (syntax or something else). If anyone can help me, I'd really appreciate.
Sorry for bad English. Thank you very much.
Nicola

when passing parameters through your function if it is called by a tkinter button you should always use the lambda statement like this: Button(finestra,text='Calcola',command=lambda: calcola(paramaters..) or the function will be called just once when the program starts.
your code:
from tkinter import *
from math import *
finestra=Tk()
finestra.geometry('800x800+300+300')
finestra.title('Dimensionamento Trasformatore')
def calcola(Vn,Vn2,Sn,Vcc,V_spira,f,Bmax,mu,J,w,Snf,N1,N2,If1,If2,kv,ki,fi,fi_c,S_colonna,S_conduttore1,S_conduttore2,Sezione_netta_cu1,Sezione_netta_cu2,Vf1,Vf2):
try:
#lettura caselle di testo/ read entry
Vn=float(Vn_s.get())
Vn2=float(Vn2_s.get())
Vcc=float(Vcc_s.get())
V_spira=float(Vspira_s.get())
Sn=float(Sn_s.get())
J=float(J_s.get())
mu=float(mu_s.get())
Bmax=float(Bmax_s.get())
f=float(f_s.get())
except ValueError:
print('inserito valore sbagliato')
else:
#calcoli / calculate
if (var_1.get()==1):
collegamento1='triangolo'
else:
collegamento1='stella'
if (var_2.get()==1):
collegamento2='triangolo'
else:
collegamento2='stella'
Snf=(Sn/3.0)
w=(2*pi*f)
if (collegamento1=='triangolo'):
Vf1=Vn
else:
Vf1=(Vn/sqrt(3))
if (collegamento2=='triangolo'):
Vf2=(Vn2)
else:
Vf2=(Vn2/sqrt(3))
N1=Vf1/V_spira
N2=Vf2/V_spira
If1=Snf/Vf1
If2=(Snf/Vf2)
kv=Vf1/Vf2
ki=If2/If1
fi=Vf1/(w*N1)
fi_c=(N1*fi)
S_colonna=(fi_c/(Bmax*sqrt(2)))
S_conduttore1=(If1/J)
S_conduttore2=(If2/J)
# Sezione_netta_cu1.set(S_conduttore1*N1/k_stip_cu)
# Sezione_netta_cu2.set(S_conduttore2*N2/k_stip_cu)
testo_23=Label(finestra,text=str(N1)).grid(sticky=W,row=4,column=5)
testo_24=Label(finestra,text=str(N2)).grid(sticky=W,row=6,column=5)
testo_25=Label(finestra,text=str(kv)).grid(sticky=W,row=11,column=5)
testo_26=Label(finestra,text=str(ki)).grid(sticky=W,row=13,column=5)
testo_27=Label(finestra,text=str(fi_c)).grid(sticky=W,row=21,column=5)
testo_28=Label(finestra,text=str(S_colonna)).grid(sticky=W,row=25,column=5)
testo_29=Label(finestra,text=str(S_conduttore1)).grid(sticky=W,row=19,column=5)
testo_30=Label(finestra,text=str(S_conduttore2)).grid(sticky=W,row=17,column=5)
## testo_31=Label(finestra,text=str(Sezione_netta_cu1)).grid(sticky=W,row=16,column=5)
## testo_32=Label(finestra,text=str(Sezione_netta_cu2)).grid(sticky=W,row=8,column=5)
## testo_33=Label(finestra,text=str(N1)).grid(sticky=W,row=14,column=5)
## testo_34=Label(finestra,text=str(N1)).grid(sticky=W,row=22,column=5)
return;
#Testi / label
testo_0=Label(finestra,text="Parametri di ingresso:").grid(sticky=W,row=0,column=0)
testo_1=Label(finestra,text="Collegamento primario:").grid(sticky=W,row=3,column=0)
testo_2=Label(finestra,text="Collegamento secondario:").grid(sticky=W,row=5,column=0)
testo_3=Label(finestra,text="Tensione nominale concatenata primaria:").grid(sticky=W,row=10,column=0)
testo_4=Label(finestra,text="Tensione nominale concatenata secondaria:").grid(sticky=W,row=12,column=0)
testo_5=Label(finestra,text="Induzione massima:").grid(sticky=W,row=20,column=0)
testo_6=Label(finestra,text="Densita di corrente:").grid(sticky=W,row=24,column=0)
testo_7=Label(finestra,text="Frequenza:").grid(sticky=W,row=18,column=0)
testo_8=Label(finestra,text="Tensione di corto circuito:").grid(sticky=W,row=16,column=0)
testo_9=Label(finestra,text="Potenza apparente nominale:").grid(sticky=W,row=8,column=0)
testo_10=Label(finestra,text="Volt-spira:").grid(sticky=W,row=14,column=0)
testo_11=Label(finestra,text="Permeabilita del ferro:").grid(sticky=W,row=22,column=0)
testo_12=Label(finestra,text="Valori calcolati:").grid(sticky=W,row=0,column=5)
testo_13=Label(finestra,text="Numero spire primario:").grid(sticky=W,row=3,column=5)
testo_14=Label(finestra,text="Numero spire secondario:").grid(sticky=W,row=5,column=5)
testo_15=Label(finestra,text="Rapporto trasformazione tensione:").grid(sticky=W,row=10,column=5)
testo_16=Label(finestra,text="Rapporto trasformazione corrente:").grid(sticky=W,row=12,column=5)
testo_17=Label(finestra,text="Flusso concatenato efficace:").grid(sticky=W,row=20,column=5)
testo_18=Label(finestra,text="Sezione colonna:").grid(sticky=W,row=24,column=5)
testo_19=Label(finestra,text="Sezione conduttore primario:").grid(sticky=W,row=18,column=5)
testo_20=Label(finestra,text="Sezione conduttore secondario:").grid(sticky=W,row=16,column=5)
testo_21=Label(finestra,text="Sezione avvolgimento primario netta:").grid(sticky=W,row=8,column=5)
testo_22=Label(finestra,text="Sezione avvolgimento secondario netta:").grid(sticky=W,row=14,column=5)
#variabili
If1=DoubleVar()
If2=DoubleVar()
N1=DoubleVar()
N2=DoubleVar()
var_1=IntVar()
var_2=IntVar()
Vn=DoubleVar()
Vf1=DoubleVar()
Vf2=DoubleVar()
Vn2=DoubleVar()
Vcc=DoubleVar()
V_spira=DoubleVar()
Sn=DoubleVar()
Snf=DoubleVar()
J=DoubleVar()
mu=DoubleVar()
Bmax=DoubleVar()
f=DoubleVar()
Vn_s=StringVar()
Vn2_s=StringVar()
Vcc_s=StringVar()
Vspira_s=StringVar()
Sn_s=StringVar()
J_s=StringVar()
mu_s=StringVar()
Bmax_s=StringVar()
f_s=StringVar()
collegamento1=StringVar()
collegamento2=StringVar()
w=DoubleVar()
kv=DoubleVar()
ki=DoubleVar()
fi=DoubleVar()
fi_c=DoubleVar()
S_colonna=DoubleVar()
S_conduttore1=DoubleVar()
S_conduttore2=DoubleVar()
Sezione_netta_cu1=DoubleVar()
Sezione_netta_cu2=DoubleVar()
#Radiobutton
#collegamento primario/ first winding
collegamentoI_1=Radiobutton(finestra,text='triangolo',value=1,variable=var_1)
collegamentoI_1.grid(row=4,column=0)
collegamentoI_2=Radiobutton(finestra,text='stella',value=2,variable=var_1)
collegamentoI_2.grid(row=4,column=1)
#collegamento secondario/ second winding
collegamentoII_1=Radiobutton(finestra,text='triangolo',value=1,variable=var_2)
collegamentoII_1.grid(row=6,column=0)
collegamentoII_2=Radiobutton(finestra,text='stella',value=2,variable=var_2)
collegamentoII_2.grid(row=6,column=1)
#caselle di testo / entry
Vn_=Entry(finestra,textvariable=Vn_s)
Vn_.grid(row=11,column=0)
Vspira_=Entry(finestra,textvariable=Vspira_s)
Vspira_.grid(row=15,column=0)
Vn2_=Entry(finestra,textvariable=Vn2_s)
Vn2_.grid(row=13,column=0)
Sn_=Entry(finestra,textvariable=Sn_s)
Sn_.grid(row=9,column=0)
Bmax_=Entry(finestra,textvariable=Bmax_s)
Bmax_.grid(row=21,column=0)
mu_=Entry(finestra,textvariable=mu_s)
mu_.grid(row=23,column=0)
Vcc_=Entry(finestra,textvariable=Vcc_s)
Vcc_.grid(row=17,column=0)
f_=Entry(finestra,textvariable=f_s)
f_.grid(row=19,column=0)
J_=Entry(finestra,textvariable=J_s)
J_.grid(row=25,column=0)
#Calculatebutton
gobutton=Button(finestra,text='Calcola',command=lambda: calcola(Vn,Vn2,Sn,Vcc,V_spira,f,Bmax,mu,J,w,Snf,N1,N2,If1,If2,kv,ki,fi,fi_c,S_colonna,S_conduttore1,S_conduttore2,Sezione_netta_cu1,Sezione_netta_cu2,Vf1,Vf2))
gobutton.grid(row=28, column=3)
finestra.mainloop()

Related

PicoCTF General Skills PW Crack Level4

I'm working on the PW Crack Level4 in the PicoCTF General Skills section. I'm very new to python and CTF's in general. The challenge is to find the right pw from the included list of 100 possibles. I could have, by now, simply entered each one, lol, but that's not the point I think. So I am trying to modify the code to iterate through the list of pw's and pass each one to the part of the code that checks it.
That's where I'm stuck. The for loop seems to run through the list without passing each pw to the part of the code that should check it... I feel like the answer is on the tip of my tongue. But I'm too new to see it.
Here's my code
import hashlib
### THIS FUNCTION WILL NOT HELP YOU FIND THE FLAG --LT ########################
def str_xor(secret, key):
#extend key to secret length
new_key = key
i = 0
while len(new_key) < len(secret):
new_key = new_key + key[i]
i = (i + 1) % len(key)
return "".join([chr(ord(secret_c) ^ ord(new_key_c)) for (secret_c,new_key_c) in zip(secret,new_key)])
###############################################################################
flag_enc = open('level4.flag.txt.enc', 'rb').read()
correct_pw_hash = open('level4.hash.bin', 'rb').read()
def hash_pw(pw_str):
pw_bytes = bytearray()
pw_bytes.extend(pw_str.encode())
m = hashlib.md5()
m.update(pw_bytes)
return m.digest()
pos_pw_list = ["6288", "6152", "4c7a", "b722", "9a6e", "6717", "4389", "1a28", "37ac", "de4f", "eb28", "351b", "3d58", "948b", "231b", "973a", "a087", "384a", "6d3c", "9065", "725c", "fd60", "4d4f", "6a60", "7213", "93e6", "8c54", "537d", "a1da", "c718", "9de8", "ebe3", "f1c5", "a0bf", "ccab", "4938", "8f97", "3327", "8029", "41f2", "a04f", "c7f9", "b453", "90a5", "25dc", "26b0", "cb42", "de89", "2451", "1dd3", "7f2c", "8919", "f3a9", "b88f", "eaa8", "776a", "6236", "98f5", "492b", "507d", "18e8", "cfb5", "76fd", "6017", "30de", "bbae", "354e", "4013", "3153", "e9cc", "cba9", "25ea", "c06c", "a166", "faf1", "2264", "2179", "cf30", "4b47", "3446", "b213", "88a3", "6253", "db88", "c38c", "a48c", "3e4f", "7208", "9dcb", "fc77", "e2cf", "8552", "f6f8", "7079", "42ef", "391e", "8a6d", "2154", "d964", "49ec"]
def level_4_pw_check():
for x in pos_pw_list: # for loop to iterate through the pos_pw_list
user_pw = input(x)
# print(user_pw) # printing user_pw just to make sure the loop is working - it is
user_pw_hash = hash_pw(user_pw)
if( user_pw_hash == correct_pw_hash ):
print("Welcome back... your flag, user:")
decryption = str_xor(flag_enc.decode(), user_pw)
print(decryption)
return
print("That password is incorrect")
level_4_pw_check()
# The strings below are 100 possibilities for the correct password.
# (Only 1 is correct)
pos_pw_list = ["6288", "6152", "4c7a", "b722", "9a6e", "6717", "4389", "1a28", "37ac", "de4f", "eb28", "351b", "3d58", "948b", "231b", "973a", "a087", "384a", "6d3c", "9065", "725c", "fd60", "4d4f", "6a60", "7213", "93e6", "8c54", "537d", "a1da", "c718", "9de8", "ebe3", "f1c5", "a0bf", "ccab", "4938", "8f97", "3327", "8029", "41f2", "a04f", "c7f9", "b453", "90a5", "25dc", "26b0", "cb42", "de89", "2451", "1dd3", "7f2c", "8919", "f3a9", "b88f", "eaa8", "776a", "6236", "98f5", "492b", "507d", "18e8", "cfb5", "76fd", "6017", "30de", "bbae", "354e", "4013", "3153", "e9cc", "cba9", "25ea", "c06c", "a166", "faf1", "2264", "2179", "cf30", "4b47", "3446", "b213", "88a3", "6253", "db88", "c38c", "a48c", "3e4f", "7208", "9dcb", "fc77", "e2cf", "8552", "f6f8", "7079", "42ef", "391e", "8a6d", "2154", "d964", "49ec"]
I'm not too experienced myself, but I think I know what you're doing wrong. I'll try to give you a small tip that will probably help you solve the problem without giving you the answer full out.
I think where you're going wrong is that you're still asking for input. Since you're comparing a list of possible passwords to the actual possible password, you don't need to ask for input anywhere in your code.
I hope this helps you out!
SO I stumbled upon the answer.... it appears to be a indent error (sorry, I don't fully grasp python). But once I properly indented my modified code I got the answer!
def level_4_pw_check():
for x in pos_pw_list: # for loop to iterate through the pos_pw_list
user_pw = x
user_pw_hash = hash_pw(user_pw)
print(user_pw) # printing user_pw just to make sure the loop is working - it is
if( user_pw_hash == correct_pw_hash ):
print("Welcome back... your flag, user:")
decryption = str_xor(flag_enc.decode(), user_pw)
#decryption = xor(flag_enc.decode(), user_pw)
print(decryption)
return
print("That password is incorrect")

Binding one combobox to another combobox in while loop in tkinter

*I wanted to bind platform_id drop combobox to teh combobox_b so taht if cpu is selected in platform_id_drop, then cpu frequencies must be listed otherwise gpu frequencies must be listed. I am using while loop to create a number of rows based on input we are giving and used dictionary to store respective columns. I am able to get only fo rone set of row i.e frequencies are display oly for one row but not for other rows. Having Problem with bind function. Please help me with this.
'''
import pandas as pd
from tkinter import filedialog
from tkinter import ttk
from tkinter.filedialog import asksaveasfile
import collections
app=Tk()
app.title("trace")
app.geometry("1000x500")
global z
required=2
z=required
global global_id
global_id=0
global text_file_3
global text_file_4
a_dict = collections.defaultdict(list)
a_dict['global_id']={}
a_dict['unique_dag_id']={}
a_dict['platform_id']={}
a_dict['deadline']={}
a_dict['wcet_cpu']={}
a_dict['wcet_gpu']={}
a_dict['input_arrival_time']={}
a_dict['hyper_period_entry']={}
a_dict['input_task_period']={}
a_dict['frequency']={}
unique_dag_id = StringVar()
wcet_cpu = StringVar()
wcet_gpu = StringVar()
deadline = StringVar()
input_arrival_time = StringVar()
hyper_period_entry = StringVar()
input_task_period=StringVar()
frequency=StringVar()
last_county=StringVar()
v=[]
dict1={'gpu':['177000000' ,'266000000' ,'350000000' ,'420000000' ,'480000000', '543000000' , '600000000'],'cpu':['200000000', '300000000', '400000000', '500000000', '600000000', '700000000', '800000000', '900000000', '1000000000' ,'1100000000', '1200000000', '1300000000', '1400000000', '1500000000' ,'1600000000', '1700000000', '1800000000', '1900000000', '2000000000']}
def save_trace1():
global global_id
global_id_info=global_id_entry
if(platform_id_drop.get()=='cpu'):
platform_id_info=0
else:
platform_id_info=1
unique_dag_id_info=unique_dag_id_entry
wcet_cpu_info=wcet_cpu_entry.get()
wcet_gpu_info=wcet_gpu_entry.get()
deadline_info=deadline_entry.get()
input_arrival_time_info=input_arrival_time_entry.get()
hyper_period_entry_info=hyper_period_entry_entry.get()
input_task_period_info=input_task_period_entry.get()
combobox_b_info=combobox_b.get()
for i in range(required):
print(a_dict['platform_id'][i].get())
global_id_label=Label(text="global_id ")
platform_id_label=Label(text='platform_id')
unique_dag_id_label=Label(text='unique_dag-id')
wcet_cpu_label=Label(text='wcet_cpu')
wcet_gpu_label=Label(text='wcet_gpu')
deadline_label=Label(text='deadline')
input_arrival_time_label=Label(text='input-arrival time')
hyper_period_entry_label=Label(text='hyper_period_entry')
input_task_period_label=Label(text='input_task_period')
freq_label=Label(text='Frequency')
platform_id_options=[
'cpu','gpu',
]
global_id_label.place(x=50,y=50)
platform_id_label.place(x=150,y=50)
unique_dag_id_label.place(x=330,y=50)
wcet_cpu_label.place(x=450,y=50)
wcet_gpu_label.place(x=600,y=50)
deadline_label.place(x=750,y=50)
input_arrival_time_label.place(x=900,y=50)
hyper_period_entry_label.place(x=1050,y=50)
input_task_period_label.place(x=1200,y=50)
freq_label.place(x=1350,y=50)
trace_entries=[]
dag_entries=[]
while(z>0):
#platform_id_drop.pack(pady=20)
def selo(eventobj):
v=[]
if(platform_id_drop.get()=='cpu'):
print("a")
v=['200000000', '300000000', '400000000', '500000000', '600000000',
'700000000', '800000000', '900000000', '1000000000' ,'1100000000', '1200000000', '1300000000', '1400000000', '1500000000' ,'1600000000', '1700000000', '1800000000', '1900000000', '2000000000']
elif(platform_id_drop.get()=='gpu'):
print("m")
v=['177000000' ,'266000000' ,'350000000' ,'420000000' ,'480000000', '543000000' , '600000000']
global_id_entry=Label(text=str(global_id))
global_id_entry.place(x=50,y=50+60*(global_id+1))
a_dict['global_id'][global_id]=global_id
unique_dag_id_entry=Label(text=str(global_id))
unique_dag_id_entry.place(x=330,y=50+60*(global_id+1))
a_dict['unique_dag_id'][global_id]=unique_dag_id_entry
wcet_cpu_entry=Entry(app)
wcet_cpu_entry.place(x=450,y=50+60*(global_id+1))
a_dict['wcet_cpu'][global_id]=wcet_cpu_entry
wcet_gpu_entry=Entry(app)
wcet_gpu_entry.place(x=600,y=50+60*(global_id+1))
a_dict['wcet_gpu'][global_id]=wcet_gpu_entry
deadline_entry=Entry(app)
deadline_entry.place(x=750,y=50+60*(global_id+1))
a_dict['deadline'][global_id]=(deadline_entry)
input_arrival_time_entry=Entry(app)
input_arrival_time_entry.place(x=900,y=50+60*(global_id+1))
a_dict['input_arrival_time'][global_id]=(input_arrival_time_entry)
hyper_period_entry_entry=Entry(app)
hyper_period_entry_entry.place(x=1050,y=50+60*(global_id+1))
a_dict['hyper_period_entry'][global_id]=(hyper_period_entry_entry)
input_task_period_entry=Entry(app)
input_task_period_entry.place(x=1200,y=50+60*(global_id+1))
a_dict['input_task_period'][global_id]=( input_task_period_entry)
platform_id_drop=ttk.Combobox(app,values=platform_id_options)
platform_id_drop.bind("<<ComboboxSelected>>",selo)
platform_id_drop.place(x=150,y=50+60*(global_id+1))
a_dict['platform_id'][global_id]=platform_id_drop
combobox_b = ttk.Combobox(app,values=v)
combobox_b.place(x=1350,y=50+60*(global_id+1))
a_dict['frequency'][global_id]=( combobox_b )
v.clear()
global_id=global_id+1
z=z-1
button=Button(app,text="save_info",command=save_trace1)
button.place(x=0,y=0)
app.mainloop()
'''

For loop doesn't go all around a dictionary

so i have the code down below
import requests
import json
with open("forex_rates.json", "r") as file:
rate = json.load(file)
nrate = rate
Base = input("enter your base currency: ")
if Base not in rate["rates"]:
print("That's not a valid currency...")
Base = input("enter your base currency: ")
with open("forex_rates.json", "r") as file:
nrate["base"] = Base
for i in rate["rates"]:
nrate["rates"][i] = rate["rates"].get(i) / rate["rates"].get(Base)
print(nrate["rates"])
I'm trying to make a program that converts different currencies, for example:
1 EUR --> 1.18 USD
and in order to do this I have to edit the forex rates everytime depending on the base value
when i finished up the code i ran t and it worked all fine and it converted all values until it hit the same value in the forex value file
like if i convert from USD it will change all currency values depending on USD but when it hits the USD in the file the loop breaks
i tried for so long 'till i tried moving USD to the very bottom of the file as there is nothing after it to break. and it worked but that's for USD only.
when i change the base value inside the program it breaks again
for people saying the code isn't even finished i'd say that i almost finished this part of the program the converting part which i believe the most difficult and any other code left is only the GUI and some multiplying math
and i'll list the forex data below
#sorry if it's too big
{
"success":true,
"timestamp":1597402446,
"base":"EUR",
"date":"2020-08-14",
"rates":{
"AED":4.335266,
"AFN":91.176403,
"ALL":123.979569,
"AMD":572.651268,
"ANG":2.125143,
"AOA":695.22591,
"ARS":86.213707,
"AUD":1.651881,
"AWG":2.124558,
"AZN":2.001576,
"BAM":1.954795,
"BBD":2.390258,
"BDT":100.546318,
"BGN":1.956895,
"BHD":0.444938,
"BIF":2283.56194,
"BMD":1.18031,
"BND":1.622912,
"BOB":8.173103,
"BRL":6.336422,
"BSD":1.183874,
"BTC":0.0001,
"BTN":88.576746,
"BWP":13.863097,
"BYN":2.914727,
"BYR":23134.077322,
"BZD":2.38624,
"CAD":1.562064,
"CDF":2302.785095,
"CHF":1.074967,
"CLF":0.033942,
"CLP":936.574514,
"CNY":8.203627,
"COP":4452.129574,
"CRC":704.672423,
"CUC":1.18031,
"CUP":31.278217,
"CVE":110.201987,
"CZK":26.106129,
"DJF":210.746982,
"DKK":7.446693,
"DOP":69.149105,
"DZD":151.514114,
"EGP":18.805169,
"ERN":17.704664,
"ETB":42.448715,
"EUR":1,
"FJD":2.523208,
"FKP":0.90119,
"GBP":0.900976,
"GEL":3.647475,
"GGP":0.90119,
"GHS":6.811663,
"GIP":0.90119,
"GMD":61.163652,
"GNF":11418.288925,
"GTQ":9.116687,
"GYD":247.470583,
"HKD":9.14817,
"HNL":29.203723,
"HRK":7.531326,
"HTG":132.978265,
"HUF":346.161502,
"IDR":17595.177253,
"ILS":4.019203,
"IMP":0.90119,
"INR":88.434024,
"IQD":1413.229387,
"IRR":49696.95603,
"ISK":161.076893,
"JEP":0.90119,
"JMD":176.632894,
"JOD":0.836814,
"JPY":125.951475,
"KES":127.822789,
"KGS":92.238283,
"KHR":4859.521032,
"KMF":491.421896,
"KPW":1062.314938,
"KRW":1401.210938,
"KWD":0.360975,
"KYD":0.986486,
"KZT":496.331879,
"LAK":10752.381531,
"LBP":1789.879783,
"LKR":216.488093,
"LRD":235.294815,
"LSL":20.549263,
"LTL":3.485149,
"LVL":0.713958,
"LYD":1.626859,
"MAD":10.913322,
"MDL":19.82872,
"MGA":4566.909302,
"MKD":61.58448,
"MMK":1610.391686,
"MNT":3362.205621,
"MOP":9.449856,
"MRO":421.37087,
"MUR":46.799002,
"MVR":18.243058,
"MWK":879.737053,
"MXN":26.199071,
"MYR":4.949633,
"MZN":83.979304,
"NAD":20.548996,
"NGN":449.107914,
"NIO":41.242296,
"NOK":10.544902,
"NPR":141.752962,
"NZD":1.80663,
"OMR":0.454403,
"PAB":1.183663,
"PEN":4.2222,
"PGK":4.165565,
"PHP":57.516411,
"PKR":199.282277,
"PLN":4.396536,
"PYG":8227.988848,
"QAR":4.297547,
"RON":4.835722,
"RSD":117.576625,
"RUB":86.625365,
"RWF":1142.595148,
"SAR":4.426709,
"SBD":9.756128,
"SCR":21.044237,
"SDG":65.300702,
"SEK":10.291595,
"SGD":1.620105,
"SHP":0.90119,
"SLL":11537.53114,
"SOS":689.301231,
"SRD":8.802808,
"STD":25132.067341,
"SVC":10.358743,
"SYP":603.981109,
"SZL":20.627972,
"THB":36.753085,
"TJS":12.208818,
"TMT":4.131085,
"TND":3.240537,
"TOP":2.698542,
"TRY":8.706498,
"TTD":8.006077,
"TWD":34.707966,
"TZS":2744.220413,
"UAH":32.433598,
"UGX":4343.852885,
"USD":1.18031,
"UYU":50.261259,
"UZS":12111.300903,
"VEF":11.788346,
"VND":27353.095658,
"VUV":134.283098,
"WST":3.09309,
"XAF":655.754247,
"XAG":0.044343,
"XAU":0.000606,
"XCD":3.189847,
"XDR":0.840933,
"XOF":655.720927,
"XPF":119.624668,
"YER":295.426891,
"ZAR":20.617975,
"ZMK":10624.212769,
"ZMW":21.85909,
"ZWL":380.05997
}
}

How do I get the sum of radio button values in Tkinter?

I have the following codes for my radio buttons and this is for my full menu programming project with tkinter:
from tkinter import *
from time import sleep
class SchoolCampMenuGUI:
def __init__(self,parent):
#------------------------------Layout Of Menu------------------------------------------#
Top=Frame(parent,bg="white")
Top.pack(side=TOP) #frame for title School Camp Menu
lblTitle=Label(Top,font=('New York Times',15),text="\t\tSchool Camp Menu\t\t\n(Please choose 1 breakfast,lunch and dinner and below 8700KJ) ")
lblTitle.pack() #setting fonts and size
f4=Label(borderwidth=3,relief=SUNKEN)
f4.pack(side=BOTTOM,fill=X)
f1=Label(borderwidth=3,relief=SUNKEN,bg="white")
f1.pack(side=LEFT) #first label for Breakfast
f2=Label(borderwidth=3,relief=SUNKEN,bg="white")
f2.pack(side=RIGHT) #second label for Lunch
f3=Label(borderwidth=3,relief=SUNKEN,bg="white")
f3.pack() #third label for dinner
def onclick1():
r.set(None)
q.set(None)
v.set(None)
def clear():
sleep(0.5)
f4.configure(text="")#define the definition of RESET button all value set to None to reselect choices and clears all calculations.
b1=Button(f4,text="RESET",width=8,bg="red",command=lambda:[onclick1(),clear()])#calling the combined function
b1.pack(side=RIGHT)
def total():
total=int(v.get())+int(r.get())+int(q.get())
f4.configure(text="Your Current Total Is: "+total+" KJs.")
r=StringVar()
v=StringVar()
q=StringVar()
r.set(0)
v.set(0)
q.set(0)
#--------------------------------------Lunch--------------------------------------#
lblMeal=Label(f3,text="Lunch",font=('arial',14,'bold'),bg="white")
lblMeal.pack()
rb1=Radiobutton(f3,text="Chicken Burgers",variable=r,font=('arial',12,'bold'),value=1180,bg="white",command=total)
rb1.pack(anchor=W)
rb2=Radiobutton(f3,text="Chicken Curry and Rice",variable=r,font=('arial',12,'bold'),value=1800,bg="white",command=total)
rb2.pack(anchor=W)
rb3=Radiobutton(f3,text="Teriyaki Chicken Sushi *Gluten Free",variable=r,font=('arial',12,'bold'),value=1730,fg="violet",command=total)
rb3.pack(anchor=W)
rb4=Radiobutton(f3,text="Caprese Panini *Gluten Free",variable=r,font=('arial',12,'bold'),value=2449,fg="violet",command=total)
rb4.pack(anchor=W)
rb5=Radiobutton(f3,text="Vegetable Risotto *Vegetarian",variable=r,font=('arial',12,'bold'),value=1432,fg="blue",command=total)
rb5.pack(anchor=W)
rb6=Radiobutton(f3,text="Gourmet Vegetable Pizza *Vegetarian",variable=r,font=('arial',12,'bold'),value=1463,fg="blue",command=total)
rb6.pack(anchor=W)
#----------------------------------Breakfast----------------------------------#
Meal=Label(f1,text="Breakfast",font=('arial',14,'bold'),bg="white")
Meal.pack()
rb7=Radiobutton(f1,text="Bacon and Egg Muffin",variable=v,font=('arial',12,'bold'),value=1240,bg="white",command=total)
rb7.pack(anchor=W)
rb8=Radiobutton(f1,text="Scrambled Eggs & Bake Beans",variable=v,font=('arial',12,'bold'),value=1533,bg="white",command=total)
rb8.pack(anchor=W)
rb9=Radiobutton(f1,text="2 Weet-Bix w/ milk",variable=v,font=('arial',12,'bold'),value=1110,bg="white",command=total)
rb9.pack(anchor=W)
rb10=Radiobutton(f1,text="Pancakes w/ syrup",variable=v,font=('arial',12,'bold'),value=2019,bg="white",command=total)
rb10.pack(anchor=W)
rb11=Radiobutton(f1,text="Bread with jam",variable=v,font=('arial',12,'bold'),value=491,bg="white",command=total)
rb11.pack(anchor=W)
rb12=Radiobutton(f1,text="Cinnamon Roll Doughnuts",variable=v,font=('arial',12,'bold'),value=1130,bg="white",command=total)
rb12.pack(anchor=W)
#----------------------------------dinner-----------------------------------#
Dinner=Label(f2,text="Dinner",font=('arial',14,'bold'),bg="white")
Dinner.pack()
rb13=Radiobutton(f2,text="Spaghetti Bolongnese",variable=q,font=('arial',12,'bold'),value=1523,bg="white",command=total)
rb13.pack(anchor=W)
rb14=Radiobutton(f2,text="Beef Burgers w/ Chips and Salad",variable=q,font=('arial',12,'bold'),value=3620,bg="white",command=total)
rb14.pack(anchor=W)
rb15=Radiobutton(f2,text="Meatball and Butter Bean Stew *Gluten Free",variable=q,font=('arial',12,'bold'),value=1820,fg="violet",command=total)
rb15.pack(anchor=W)
rb16=Radiobutton(f2,text="Roast Beef *Gluten Free",variable=q,font=('arial',12,'bold'),value=2280,fg="violet",command=total)
rb16.pack(anchor=W)
rb17=Radiobutton(f2,text="Creamy Broccoli Gnocchi *Vegetarian",variable=q,font=('arial',12,'bold'),value=2800,fg="blue",command=total)
rb17.pack(anchor=W)
rb18=Radiobutton(f2,text="Vegetable Wellington *Vegetarian",variable=q,font=('arial',12,'bold'),value=2270,fg="blue",command=total)
rb18.pack(anchor=W)
Is there a way to add all values together but not getting them? This is for my school menu project. Any help appreciated.
Note: The values are in KJs for food. So far I have all the values but they are just put there, e.g. 11801800, but not adding it up. I used r.get()+v.get() but they don't actually add the values up.
They do add up. Your problem is that r.get() returns a string, not an integer. First convert them, then sum up.
int(r.get()) + int(v.get())

Unhandled exception in py2neo: Type error

I am writing an application whose purpose is to create a graph from a journal dataset. The dataset was a xml file which was parsed in order to extract leaf data. Using this list I wrote a py2neo script to create the graph. The file is attached to this message.
As the script was processed an exception was raised:
The debugged program raised the exception unhandled TypeError
"(1676 {"titulo":"reconhecimento e agrupamento de objetos de aprendizagem semelhantes"})"
File: /usr/lib/python2.7/site-packages/py2neo-1.5.1-py2.7.egg/py2neo/neo4j.py, Line: 472
I don't know how to handle this. I think that the code is syntactically correct...but...
I dont know if I shoud post the entire code here, so the code is at: https://gist.github.com/herlimenezes/6867518
There goes the code:
+++++++++++++++++++++++++++++++++++
'
#!/usr/bin/env python
#
from py2neo import neo4j, cypher
from py2neo import node, rel
# calls database service of Neo4j
#
graph_db = neo4j.GraphDatabaseService("DEFAULT_DOMAIN")
#
# following nigel small suggestion in http://stackoverflow.com
#
titulo_index = graph_db.get_or_create_index(neo4j.Node, "titulo")
autores_index = graph_db.get_or_create_index(neo4j.Node, "autores")
keyword_index = graph_db.get_or_create_index(neo4j.Node, "keywords")
dataPub_index = graph_db.get_or_create_index(neo4j.Node, "data")
#
# to begin, database clear...
graph_db.clear() # not sure if this really works...let's check...
#
# the big list, next version this is supposed to be read from a file...
#
listaBase = [['2007-12-18'], ['RECONHECIMENTO E AGRUPAMENTO DE OBJETOS DE APRENDIZAGEM SEMELHANTES'], ['Raphael Ghelman', 'SWMS', 'MHLB', 'RNM'], ['Objetos de Aprendizagem', u'Personaliza\xe7\xe3o', u'Perfil do Usu\xe1rio', u'Padr\xf5es de Metadados', u'Vers\xf5es de Objetos de Aprendizagem', 'Agrupamento de Objetos Similares'], ['2007-12-18'], [u'LOCPN: REDES DE PETRI COLORIDAS NA PRODU\xc7\xc3O DE OBJETOS DE APRENDIZAGEM'], [u'Maria de F\xe1tima Costa de Souza', 'Danielo G. Gomes', 'GCB', 'CTS', u'Jos\xe9 ACCF', 'MCP', 'RMCA'], ['Objetos de Aprendizagem', 'Modelo de Processo', 'Redes de Petri Colorida', u'Especifica\xe7\xe3o formal'], ['2007-12-18'], [u'COMPUTA\xc7\xc3O M\xd3VEL E UB\xcdQUA NO CONTEXTO DE UMA GRADUA\xc7\xc3O DE REFER\xcaNCIA'], ['JB', 'RH', 'SR', u'S\xe9rgio CCSPinto', u'D\xe9bora NFB'], [u'Computa\xe7\xe3o M\xf3vel e Ub\xedqua', u'Gradua\xe7\xe3o de Refer\xeancia', u' Educa\xe7\xe3o Ub\xedqua']]
#
pedacos = [listaBase[i:i+4] for i in range(0, len(listaBase), 4)] # pedacos = chunks
#
# lists to collect indexed nodes: is it really useful???
# let's think about it when optimizing code...
dataPub_nodes = []
titulo_nodes = []
autores_nodes = []
keyword_nodes = []
#
#
for i in range(0, len(pedacos)):
# fill dataPub_nodes and titulo_nodes with content.
#dataPub_nodes.append(dataPub_index.get_or_create("data", pedacos[i][0], {"data":pedacos[i][0]})) # Publication date nodes...
dataPub_nodes.append(dataPub_index.get_or_create("data", str(pedacos[i][0]).strip('[]'), {"data":str(pedacos[i][0]).strip('[]')}))
# ------------------------------- Exception raised here... --------------------------------
# The debugged program raised the exception unhandled TypeError
#"(1649 {"titulo":["RECONHECIMENTO E AGRUPAMENTO DE OBJETOS DE APRENDIZAGEM SEMELHANTES"]})"
#File: /usr/lib/python2.7/site-packages/py2neo-1.5.1-py2.7.egg/py2neo/neo4j.py, Line: 472
# ------------------------------ What happened??? ----------------------------------------
titulo_nodes.append(titulo_index.get_or_create("titulo", str(pedacos[i][1]).strip('[]'), {"titulo":str(pedacos[i][1]).strip('[]')})) # title node...
# creates relationship publicacao
publicacao = graph_db.get_or_create_relationships(titulo_nodes[i], "publicado_em", dataPub_nodes[i])
# now processing autores sublist and collecting in autores_nodes
#
for j in range(0, len(pedacos[i][2])):
# fill autores_nodes list
autores_nodes.append(autores_index.get_or_create("autor", pedacos[i][2][j], {"autor":pedacos[i][2][j]}))
# creates autoria relationship...
#
autoria = graph_db.get_or_create_relationships(titulo_nodes[i], "tem_como_autor", autores_nodes[j])
# same logic...
#
for k in range(0, len(pedacos[i][3])):
keyword_nodes.append(keyword_index.get_or_create("keyword", pedacos[i][3][k]))
# cria o relacionamento 'tem_como_keyword'
tem_keyword = graph_db.get_or_create_relationships(titulo_nodes[i], "tem_como_keyword", keyword_nodes[k])
`
The fragment of py2neo which raised the exception
def get_or_create_relationships(self, *abstracts):
""" Fetch or create relationships with the specified criteria depending
on whether or not such relationships exist. Each relationship
descriptor should be a tuple of (start, type, end) or (start, type,
end, data) where start and end are either existing :py:class:`Node`
instances or :py:const:`None` (both nodes cannot be :py:const:`None`).
Uses Cypher `CREATE UNIQUE` clause, raising
:py:class:`NotImplementedError` if server support not available.
.. deprecated:: 1.5
use either :py:func:`WriteBatch.get_or_create_relationship` or
:py:func:`Path.get_or_create` instead.
"""
batch = WriteBatch(self)
for abstract in abstracts:
if 3 <= len(abstract) <= 4:
batch.get_or_create_relationship(*abstract)
else:
raise TypeError(abstract) # this is the 472 line.
try:
return batch.submit()
except cypher.CypherError:
raise NotImplementedError(
"The Neo4j server at <{0}> does not support " \
"Cypher CREATE UNIQUE clauses or the query contains " \
"an unsupported property type".format(self.__uri__)
)
======
Any help?
I have already fixed it, thanks to Nigel Small. I made a mistake as I wrote the line on creating relationships. I typed:
publicacao = graph_db.get_or_create_relationships(titulo_nodes[i], "publicado_em", dataPub_nodes[i])
and it must to be:
publicacao = graph_db.get_or_create_relationships((titulo_nodes[i], "publicado_em", dataPub_nodes[i]))
By the way, there is also another coding error:
keyword_nodes.append(keyword_index.get_or_create("keyword", pedacos[i][3][k]))
must be
keyword_nodes.append(keyword_index.get_or_create("keyword", pedacos[i][3][k], {"keyword":pedacos[i][3][k]}))

Categories

Resources