How do I get the sum of radio button values in Tkinter? - python
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())
Related
I cant print horizontally
I want to make a book catalog, the output is to print horizontally and change line for every 3 books. I understand that we can do a print horizontal by using: end = "" BUT that only works for 1 line. As my output has 3 line like Title, ISBN, Price, if I using end = "", it can't get it done. Below is my code line_format = "{:50s} \n{:6s} - {:13s} \n{:11s}" books = db.get_books(kel) for book in books: print((line_format.format(str(book.title), str(book.isbn), "Rp. {:,}".format(book.price).replace(",",".")))) What I got is: Deaver - Never Game A/UK 9780008303778 Rp. 161.000 Poirot - DEATH ON THE NILE (Exp] 9780008328948 Rp. 28.000 Alchemist - 25th Anniv ed 9780062355300 Rp. 160.000 Finn- Woman in the Window [MTI] 9780062906137 Rp. 162.000 Mahurin- Blood & Honey 9780063041172 Rp. 62.000 What I want for the output is: Deaver - Never Game DEATH ON THE NILE (Exp] Alchemist 9780008303778 9780008328948 9780062355300 Rp. 161.000 Rp. 28.000 Rp. 160.000 Woman in the Window Blood & Honey 9780062906137 9780063041172 Rp. 162.000 Rp. 62.000
webscraping with selenium to click a button and grab everything
I have been working on this scraper for a while and I think it could be improved but I'm not sure where to go from here. The initial scraper looks like this and I believe it does everything I need it to do: url = "https://matrix.heartlandmls.com/Matrix/Public/Portal.aspx?L=1&k=990316X949Z&p=DE-74613894-421" h_table = [] driver = webdriver.Firefox() driver.get(url) driver.find_element_by_xpath("/html/body/form/div[3]/div/div/div[5]/div[3]/span[2]/div/div/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/span/a").click() time.sleep(10) i = 200 while i > 0: h_table.append(driver.find_element_by_id("wrapperTable").text) driver.find_element_by_xpath("/html/body/form/div[3]/div/div/div[5]/div[2]/div/div[1]/div/div/span/ul/li[2]/a").click() time.sleep(10) i -= 1 this outputs everything into a table which i can clean up ['210 Sitter Street\nPleasant Hill, MO 64080\nMLS#:2178982\nMap\n$15,000\nSold\n4Bedrms\n2Full Bath(s)\n0Half Bath(s)\n1,848Sqft\nBuilt in1950\n0.27Acres\nSingle Family\n1 / 10\nThis Home sits on a level, treed, and nice .279 acre sizeable double lot. The property per taxes, is identified as a Single Family Home however it has 2 separate utility meters and 2 living spaces, each with 2 bedrooms and 1 full bath and laundry areas, and was utilized as a Duplex for Rental income for 2 units. This property is a CASH ONLY sale and is being sold "In It\'s Present Condition". Home and detached garage are in need of repair OR would be a candidate for a tear down and complete rebuild on the lot.\nAbout 210 Sitter Street, Pleasant Hill, MO 64080\nDirections:I-70 to 7 Hwy, to Broadway, to Sitter St, to property.\nGeneral Description\nMLS Number\n2178982\nCounty\nCass\nCity\nPleasant Hill\nSub Div\nWalkers & Sitlers\nType\nSingle Family\nFloor Plan Description\nRanch\nBdrms\n4\nBaths Full\n2\nBaths Half\n0\nAge Description\n51-75 Years\nYear Built\n1950\nSqft Main\n1848\nSQFT MAIN SOURCE\nPublic Record\nBelow Grade Finished Sq Ft\n0\nBelow Grade Finished Sq Ft Source\nPublic Record\nSqft\n1848\nLot Size\n12,155\nAcres\n0.27\nSchools E\nPleasant Hill Prim\nSchools M\nPleasant Hill\nSchools H\nPleasant Hill\nSchool District\nPleasant Hill\nLegal Description\nWALKER & SITLERS LOT 47 & 48 BLK 5\nS Terms\nCash\nInterior Features\nFireplace?\nY\nFireplace Description\nLiving Room, Wood Burning\nBasement\nN\nBasement Description\nBlock, Crawl Space\nDining Area Description\nEat-In Kitchen\nUtility Room\nMultiple, Main Level\nInterior Features\nFixer Up\nRooms\nBathroom Full\nLevel 1\n2nd Full Bath\nLevel 1\nMaster Bedroom\nLevel 1\nSecond Bedroom\nLevel 1\nMaster BR- 2nd\nLevel 1\nFourth Bedroom\nLevel 1\nKitchen\nLevel 1\nKitchen- 2nd\nLevel 1\nLiving Room\nLevel 1\nFamily Rm- 2nd\nLevel 1\nExterior / Construction\nGarage/Parking?\nY\nGarage/Parking #\n2\nGarage Description\nDetached, Front Entry\nConstruction\nFrame\nArchitecture\nTraditional\nRoof\nComposition\nLot Description\nCity Limits, City Lot, Level, Treed\nIn Floodplain\nNo\nInside City Limits\nYes\nStreet Maintenance\nPub Maint, Paved\nExterior Features\nFixer Up\nUtility Information\nCentral Air\nY\nHeat\nForced Air Gas\nCool\nCentral Electric, Window Unit(s)\nWater\nCity/Public\nSewer\nCity/Public\nFinancial Information\nS Terms\nCash\nHoa Amount\n$0\nTax\n$1,066\nSpecial Tax\n$0\nTotal Tax\n$1,066\nExclusions\nEntire Property\nType Of Ownership\nPrivate\nWill Sell\nCash\nAssessment & Tax\nAssessment Year\n2019\n2018\n2017\nAssessed Value - Total\n$17,240\n$15,380\n$15,380\nAssessed Value - Land\n$2,400\n$1,920\n$1,920\nAssessed Value - Improved\n$14,840\n$13,460\n$13,460\nYOY Change ($)\n$1,860\n$\nYOY Change (%)\n12%\n0%\nTax Year\n2019\n2018\n2017\nTotal Tax\n$1,178.32\n$1,065.64\n$1,064.30\nYOY Change ($)\n$113\n$1\nYOY Change (%)\n11%\n0%\nNotes for you and your agent\nAdd Note\nMap data ©2020\nTerms of Use\nReport a map error\nMap\n200 ft \nParcel Disclaimer' however, I had seen some other examples with WebDriverWait, but so far I have been unsuccessful, I think it would greatly speed up the scraper, here's the code I wrote from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC url = "https://matrix.heartlandmls.com/Matrix/Public/Portal.aspx?L=1&k=990316X949Z&p=DE-74613894-421" h_table = [] xpath = '/html/body/form/div[3]/div/div/div[5]/div[2]/div/div[1]/div/div/span/ul/li[2]/a' driver = webdriver.Firefox() driver.get(url) driver.find_element_by_xpath("/html/body/form/div[3]/div/div/div[5]/div[3]/span[2]/div/div/div[2]/div[1]/div/div/div[2]/div[2]/div[1]/span/a").click() time.sleep(10) while True: button = driver.find_elements_by_xpath("/html/body/form/div[3]/div/div/div[5]/div[2]/div/div[1]/div/div/span/ul/li[2]/a") if len(button) < 1: print('done') break else: h_table.append(driver.find_element_by_id("wrapperTable").text) WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, 'xpath'))).click() this seems to give all the results, but it gives duplicates and I couldn't stop it without a keyboard interrupt calling len(h_table) = 258, where it should be 200
if the length of your list is the problem, why not using : if len(h_table) >= 200: print("done") break
confusion about creating a conversational alexa skill using Flask-Ask and python: it goes to FallBackIntent when required slot missing
I want to create a conversational alexa skill using Flask-Ask and python 3. But when I intentionally omit the required slot. Alexa doesn't prompt me anything. It goes to FallBackIntent directly. I've set the prompt and corresponding answer for it in the web console and I've added necessary code to check if dialogState!= 'COMPLETED' and return delegate(). But it just go to FallBackIntent directly. Below is a screenshot of my settings for the slot on the web console Below is my entire code(I use ngrok to map to my localhost): from flask import Flask from flask_ask import Ask, statement, question, session, convert_errors, delegate import random import logging app = Flask(__name__) ask = Ask(app, "/ask_demo") app.logger.setLevel(logging.DEBUG) logger = app.logger facts = ['A year on Mercury is just 88 days long.', 'Despite being farther from the Sun, Venus experiences higher temperatures than Mercury.', 'Venus rotates counter-clockwise, possibly because of a collision in the past with an asteroid.', 'On Mars, the Sun appears about half the size as it does on Earth.', 'Earth is the only planet not named after a god.', 'Jupiter has the shortest day of all the planets.', 'The Milky Way galaxy will collide with the Andromeda Galaxy in about 5 billion years.', 'The Sun contains 99.86% of the mass in the Solar System.', 'The Sun is an almost perfect sphere.', 'A total solar eclipse can happen once every 1 to 2 years. This makes them a rare event.', 'Saturn radiates two and a half times more energy into space than it receives from the sun.', 'The temperature inside the Sun can reach 15 million degrees Celsius.', 'The Moon is moving approximately 3.8 cm away from our planet every year.',] fact_index_by_planets =dict() fact_index_by_planets['mercury'] = [0] fact_index_by_planets['venus'] = [1,2] fact_index_by_planets['mars'] = [3] fact_index_by_planets['earth'] = [4] fact_index_by_planets['jupiter'] = [5] fact_index_by_planets['sun'] = [7,8,9,11] fact_index_by_planets['saturn'] = [10] fact_index_by_planets['moon'] = [12] sample_questions = 'What planet do you ask for, you can say a fact about Mercury, Venus, Mars, Earth, Jupiter, Sun, ' \ 'Saturn or Moon?' def get_dialog_state(): return session['dialogState'] def get_fact(planet): planet = planet.lower() indices = fact_index_by_planets[planet] index = random.choice(indices) return facts[index] # #app.route('/',methods=['GET']) # def homepage(): # return "hi this is the homepage!" #ask.launch def start_skill(): welcome_message = 'Hello there, Welcome! {}'.format(sample_questions) logger.debug('Launch') return question(welcome_message) #ask.intent("FactIntent") def tell_fact(planet): dialog_state = get_dialog_state() if dialog_state != 'COMPLETED': return delegate() logger.debug("The planet asked for is: {}".format(planet)) if convert_errors and 'planet' in convert_errors: return question("Can you please repeat the planet name, you can say Mercury, Venus, Mars, Earth, Jupiter, Sun, Saturn or Moon?") fact_msg = get_fact(planet) return question(fact_msg+"Anything else?") #ask.intent("AMAZON.StopIntent") def stop(str): logger.debug('Stop') return statement('Thank you for using me! See you') #ask.intent('AMAZON.FallbackIntent') def fall_back(): logger.debug('Not Understood') return question("Sorry! I don't understand Could you repeat that?") if __name__ == '__main__': app.run(debug=True, port=3000) Could anyone tell me what is wrong with my code? Thank you!
Tkinter error type variable [duplicate]
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()
Python QtreeWidget: return tree hierarchy
I got stuck in trying to obtain the hierarchical view of a widget tree. The code works fine and generates a nice tree like that: ROOT(Animal): | | |___Not extinct: . | (red) . |_____BIRD--------------(blue) . | (green) | | (red) |_____Mammal------------(blue) | (green) | | (red) |_____Reptile-----------(blue) (green) Here is the code with the tree hierarchy: def myTreeWDG(self): .... """define tree""" self.obj_animalTreeWDG = QtGui.QTreeWidget(self.obj_viewGroupBox) self.obj_animalTreeWDG.setGeometry(QtCore.QRect(10, 20, 191, 131)) self.obj_animalTreeWDG.setObjectName("obj_animalTreeWDG") """ROOT: animal""" obj_parent1 = QtGui.QTreeWidgetItem(self.obj_animalTreeWDG) """not extinct:""" obj_childView1_1 = QtGui.QTreeWidgetItem() obj_parent1.addChild(obj_childView1_1) """bird""" obj_childView1_1_1 = QtGui.QTreeWidgetItem() obj_childView1_1.addChild(obj_childView1_1_1) """3: red, blue, green""" total=3 self.insert_treeLeaves(total,obj_childView1_1_1) """mamal""" obj_childView1_1_2 = QtGui.QTreeWidgetItem() obj_childView1_1.addChild(obj_childView1_1_2) """3: red, blue, green""" total=3 self.insert_treeLeaves(total,obj_childView1_1_2) """reptile""" obj_childView1_1_3 = QtGui.QTreeWidgetItem() obj_childView1_1.addChild(obj_childView1_1_3) """3: red, blue, green""" total=3 self.insert_treeLeaves(total,obj_childView1_1_3) """connect event""" QtCore.QObject.connect(self.obj_animalTreeWDG, QtCore.SIGNAL('itemClicked(QTreeWidgetItem*, int)'), self.obj_treeViewInput) Here is the code to add the leaves into the tree: def insert_treeLeaves(self,total,tree_directParent): for i in range(0,total): """leaves with color name""" tree_child_leaf = QtGui.QTreeWidgetItem() tree_directParent.addChild(tree_child_leaf) Then, we have the function that tells us every time the tree is clicked, and where it was clicked: def obj_treeViewInput(self,item,col): print "obj _Qtree : pressed" print "name:" item.text(col) The problem is, how can we get if the touched leaf (red) belongs to the Bird or other father, i.e. how to get the following output give some mouse click: Animal - Not extinct - Mammal - (red). All comments and suggestions are highly appreciated.
What about a method in each QtreeWidgetItem in which you could print the path to this item. In this method, you could use recursion to get the complete path of the item's parents (you have a "QTreeWidgetItem * parent () const" method to do this) and you add the current item's text to its parent's path ! You stop the recursion when an item do not have any parent. I hope I understood your question and this helps you a little bit ! Do you have your own QTreeWidgetItem class ? You could use a specific role to achieve this...