Python tkinter calculate student status - python

I am working on a python Tkinter assignment in which an input box accepts user input and then displays the GPA and student status. Im pretty sure I have this setup wrong and am looking for advice on how to use an If statement to determine student status. Should everything fall under the getStudentStatus function or is it better to have two functions?
import math
from tkinter import *
#calculate student status
def getStudentStatus():
data = float(inputGPA.get())
floatedGPA = (data)
#Print student status
label2 = Label(GPA, text = 'Your GPA is:' ' %.2f' % floatedGPA).grid(row = 3, column = 0)
label3 = Label(GPA, getStanding).grid(row = 4, column = 0)
return
def getStanding():
#Get academic Status
if(data>=3.5):
return("This student is on the Deans List")
elif(data>=2.0):
return("This student is on Acedmic Probation")
else:
return("This student has Regular Standing")
#define window
GPA = Tk()
GPA.title("GPA Tool")
GPA.geometry("200x200")
#define variables
inputGPA = StringVar()
#label for text box
label1 = Label(GPA, text="Enter your GPA: ").grid(row = 0, column = 0)
#entry text box
entry1 = Entry(GPA, textvariable = inputGPA).grid(row = 1, column = 0)
#submit button
button1 = Button(GPA, text="Submit", command=getStudentStatus).grid(row = 2, column = 0)
GPA.mainloop()

To avoid that a new label is created on every button press, you could create an empty label outside of the function.
To assign the label object to a variable, split the creation and the placement.
In the function you could configure the label and add the wanted output.
Additionally you need to pass the float to the second function so that the comparison operators have a value to compare.
import math
from tkinter import *
#calculate student status
def getStudentStatus():
data = float(inputGPA.get())
floatedGPA = (data)
#Print student status
label2.configure(text = 'Your GPA is:' ' %.2f' % floatedGPA)
label3.configure(text = getStanding(floatedGPA))
def getStanding(data):
#Get academic Status
if(data>=3.5):
return("This student is on the Deans List")
elif(data>=2.0):
return("This student is on Acedmic Probation")
else:
return("This student has Regular Standing")
#define window
GPA = Tk()
GPA.title("GPA Tool")
GPA.geometry("200x200")
#define variables
inputGPA = StringVar()
#label for text box
label1 = Label(GPA, text="Enter your GPA: ").grid(row = 0, column = 0)
#entry text box
entry1 = Entry(GPA, textvariable = inputGPA).grid(row = 1, column = 0)
# create empty labels
label2 = Label(GPA, text = '')
label3 = Label(GPA, text='')
# place empty labels
label2.grid(row = 3, column = 0)
label3.grid(row = 4, column = 0)
#submit button
button1 = Button(GPA, text="Submit", command=getStudentStatus).grid(row = 2, column = 0)
GPA.mainloop()

Related

Populating a shelf in python using a text box for input in Tkinter

When using a radio button in the GUI I am able to launch a text box for input which calls a function set_name
When I look at the .dir file that the shelf contains it will not have any of the input
My code is below thanks for any help
from tkinter import *
import shelve
class MyFrame (Frame):
def __init__(self):
Frame.__init__(self)
self.master.geometry("600x600")
self.master.title("Student Scores")
self.grid()
#open text file
student_scores = shelve.open('student_name', 'c')
#Display menue here here
self.student_name = StringVar()
# Prompt, Entry and Button
self.prompt = Label(self, text = "Select one of the 3 menu options")
self.prompt.grid(row = 0, column = 0)
#Radio Button Menu options
self.button_selected = IntVar()
self.menu_button = Radiobutton(self, text = "Add student name",
variable = self.button_selected, value=1,
command = self.set_name)
self.menu_button.grid(row = 3, column = 0)
print(list(student_scores.keys()))
#close test file
student_scores.close()
#Create functions for radio button
def set_name(self):
self.prompt = Label(self, text = "Enter students name: ")
self.prompt.grid(row = 7, column = 0)
self.input = Entry(self)
self.input.grid(row = 7, column = 1)
self.button_submit = Button(self, text = "Submit",
command = self.submit_click)
self.button_submit.grid(row = 7, column = 2)
def submit_click(self):
#self.student_name.set(self.input.get())
print("button clicked")
asn_frame = MyFrame()
asn_frame.mainloop()
Im just expecting to do a simple populating of a text box input as entered and have it populate a shelf in python

How do I use grid system on entry widget affected by .get()

my code:
import tkinter as tk
from tkinter import *
truth = ""
us = ""
uss = ""
root = Tk()
s = Label(root, text = ".")
s.grid(row = 1, column = 1)
wel = Label(root, text = "whats your email")
wel.grid(row = 1, column = 5)
inp = Entry(root).get()
inp.grid(row = 3, column = 5)
def callback():
us = inp[:inp.index("#")]
uss = inp[inp.index("#")+1:]
truth =us, " is username, and ", uss,"is domain"
print(truth)
sub = Button(root, text = "submit", command = callback)
sub.grid(row = 5, column = 5)
final = Label(root, textvariable = truth)
final.grid(row = 5, column = 6)
root.mainloop()
Then I get an error message:
'str' object has no attribute 'grid'
How do I use grid system on entry widget affected by .get()?

How to save an entry in Tkinter to later use in a calculation, then print the answer inside the Tkinter window

I am trying to make a program which calculates 3-4 values using some user inputted values
I have tried making a function which saves the entries into variables, and making the variables global but that didn't work
from tkinter import *
from math import *
root = Tk()
label1 = Label(root, text = "Enter value for length ")
label1.grid(columnspan = 2, sticky = "W")
length = Entry(root)
length.grid(row = 0, column = 2)
label2 = Label(root, text = "Enter value for volume ")
label2.grid(columnspan = 2, sticky = "W")
volume = Entry(root)
volume.grid(row = 1, column = 2)
label3 = Label(root, text = "Enter value for the thickness of the cylinder ")
label3.grid(columnspan = 2, sticky = "W")
thickness = Entry(root)
thickness.grid(row = 2, column = 2)
label4 = Label(root, text = "Enter value for starting temperature ")
label4.grid(columnspan = 2, sticky = "W")
st_T = Entry(root)
st_T.grid(row = 3, column = 2)
label5 = Label(root, text = "Enter value for finishing temperature ")
label5.grid(columnspan = 2, sticky = "W")
end_T = Entry(root)
end_T.grid(row = 4, column = 2)
def save():
v = volume.get()
l = length.get()
w = thickness.get()
t0 = st_T.get()
t1 = end_T.get()
global values
values = [v, l, w, t1, t0]
Button(root, text = "Submit", command = save).grid(row = 6, column = 0)
root.mainloop()
I know the current code isn't very pretty and is very inefficient but the error keeps saying that v is not defined
You might consider declaring a variable, or a an instance of a context object (that you will define) at global scope to store your user inputs.
Then you will be able to read the user inputs later in another function.
Do not forget to use the keyword 'global' before modifying the global object in a different scope (like in a function). Have a look here : https://www.geeksforgeeks.org/global-keyword-in-python/
By example you could declare your global object/variable/whatever you need, along with your root Tkinter object.

Tip calculator - syntax error

Hello guys im new to programming relatively, but all the same im trying to use a GUI interface to build a tip calculator. nothing big, nothing relatively hard, but im running into errors. for some reason my Python wont show the errors. it just goes to the shell, says SyntaxError: and then quits back to the script. it used to show the errors but i dont know whats wrong... anyways if you guys could help me troubleshoot this id greatly appreciate it..
`
# A tip calculator
# A tip calculator using a GUI interface
# Austin Howard Aug - 13 - 2014
from tkinter import *
#Creating buttons.
class Calculator(Frame):
""" A GUI tip calculator."""
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.creating_buttons()
def creating_buttons(self):
"""This list includes Entry fields, which the user will use to define
several objects such as Bill, and how many people are paying on that bill."""
#Create an entry field button for how much the bill total is.
#Create a label
bill_lbl = Label(self,
text = "Bill: ")
bill_lbl.grid(row = 1,
column = 0,
columnspan = 1,
sticky = W)
#Create an Entry field.
bill_ent = Entry(self)
bill_ent.grid(row = 1,
column = 1,
sticky = W)
#Create a Button for how many people will be paying on the bill
#Create label
people_paying_lbl = Label(self,
text = "How many people are paying on this bill?: ")
people_paying_lbl.grid(row = 2,
column = 0,
columnspan = 1,
sticky = W)
#Create an entry field
people_paying_ent = Entry(self)
people_paying_ent.grid(row = 2,
column = 1,
sticky = W)
#Create a text box to display the totals in
bill_total_txt = Text(self,
width = 40,
height = 40,
wrap = WORD)
bill_total_txt.grid(row = 3,
column = 0,
columnspan = 2,
sticky = W)
#Create a Submit button
submit = Button(self,
text = "Submit",
command = self.total)
submit.grid(row = 4,
column = 0,
sticky = W)
def total(self):
""" Takes the values from Bill, and # of people to get the amount that will be
displayed in the text box."""
TAX = .15
bill = float(bill_ent)
people = people_paying_ent
Total = ("The tip is: $", TAX * bill, "\nThe total for the bill is: $",
TAX * bill + bill,
"divided among the people paying equally is: $",
TAX * bill + bill / people "per, person.")
bill_total_txt.delete(0.0, END)
bill_total_txt.insert(0.0, Total)
#Starting the Program
root = Tk()
root.title("Tip Calculator")
app = Calculator(root)
root.mainloop()
`
You have an error on line 68:
Replace
TAX * bill + bill / people "per, person.")
with
TAX * bill + bill / people, "per, person.")
Also make sure you remove the backtick after root.mainloop()
Your way of getting the input from the Entry boxes is wrong. You should bind a StringVariable to them, to later be able to get what the user typed:
self.billvar = StringVar()
bill_ent = Entry(self, textvariable = self.billvar)
And the same for the number of people box.
Then in your total function you can read the values by using self.billvar.get(). You can convert this to a float using float(self.billvar.get()). However, when this fails (the user typed in something that can not be converted to a float) you probably want to tell them instead of having the program throwing an error. So you should use something like:
try:
convert input
except:
what to do if it fails, tell the user?
else:
what to do if it did not fail, so do the calculations
Your program then becomes something like this (I made comments with ##):
# A tip calculator
# A tip calculator using a GUI interface
# Austin Howard Aug - 13 - 2014
from tkinter import *
#Creating buttons.
class Calculator(Frame):
""" A GUI tip calculator."""
def __init__(self, master):
Frame.__init__(self, master)
self.grid()
self.creating_buttons()
def creating_buttons(self):
"""This list includes Entry fields, which the user will use to define
several objects such as Bill, and how many people are paying on that bill."""
#Create an entry field button for how much the bill total is.
#Create a label
bill_lbl = Label(self,
text = "Bill: ")
bill_lbl.grid(row = 1,
column = 0,
columnspan = 1,
sticky = W)
#Create an Entry field.
## Create a StringVar and link it to the entry box
self.billvar = StringVar()
bill_ent = Entry(self, textvariable = self.billvar)
bill_ent.grid(row = 1,
column = 1,
sticky = W)
#Create a Button for how many people will be paying on the bill
#Create label
people_paying_lbl = Label(self,
text = "How many people are paying on this bill?: ")
people_paying_lbl.grid(row = 2,
column = 0,
columnspan = 1,
sticky = W)
#Create an entry field
## Create a StringVar and link it to the entry box
self.pplvar = StringVar()
people_paying_ent = Entry(self, textvariable = self.pplvar)
people_paying_ent.grid(row = 2,
column = 1,
sticky = W)
#Create a text box to display the totals in
## This had to be self.bill_total_txt, to be able to put text in it from the total function
self.bill_total_txt = Text(self,
height = 10,
width = 40,
wrap = WORD)
self.bill_total_txt.grid(row = 3,
column = 0,
columnspan = 2,
sticky = W)
#Create a Submit button
submit = Button(self,
text = "Submit",
command = self.total)
submit.grid(row = 4,
column = 0,
sticky = W)
def total(self):
""" Takes the values from Bill, and # of people to get the amount that will be
displayed in the text box."""
TAX = .15
## Try to convert the bill to a float and the number of people to an integer
try:
bill = float(self.billvar.get())
people = int(self.pplvar.get())
## If something goes wrong tell the user the input is invalid
except:
self.bill_total_txt.delete(0.0, END)
self.bill_total_txt.insert(0.0, 'Invalid input')
## If the conversion was possible, calculate the tip, the total amount and the amout per person and format them as a string with two decimals
## Then create the complete message as a list and join it togeather when writing it to the textbox
else:
tip = "%.2f" % (TAX * bill)
tot = "%.2f" % (TAX * bill + bill)
tot_pp = "%.2f" % ((TAX * bill + bill) / people)
Total = ["The tip is: $", tip,
"\nThe total for the bill is: $",
tot,
" divided among the people paying equally is: $",
tot_pp,
" per person."]
self.bill_total_txt.delete(0.0, END)
self.bill_total_txt.insert(0.0, ''.join(Total))
#Starting the Program
root = Tk()
root.title("Tip Calculator")
app = Calculator(root)
root.mainloop()

Python - RadioButton - assigning a value i can use?

I have a python assignment to do for University but I am having a problem.The assignment states that I need to create checkbox buttons that have a value that will total once I push a button. This I have managed to do. I have to do the same thing with radio buttons and here I am having a problem. If I create the radio buttons they work, but i do not how to assign a value to them and then use this value in my gandTotal.
`enter code here``#Help with the menu program
import random
from Tkinter import *
class App(Frame):
#GUI application
def __init__(self,master):
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
#Create all the widgets here
#Label to welcome the user
Label(self,text = "Welcome to Awesome Reasturant:"
).grid(row=1,column=0,sticky=W)
#..........your code goes here
#Labels to request the name of the customer
Label(self,text = "Customer Name:"
).grid(row=2,column=0,sticky=W)
self.CustomerName_ent = Entry(self)
self.CustomerName_ent.grid(row = 2, column = 1, sticky = W)
#Labels to request the telephone number
Label(self,text = "Telephone Number:"
).grid(row=3,column=0,sticky=W)
self.Telephone_ent = Entry(self)
self.Telephone_ent.grid(row = 3, column = 1, sticky = W)
#Label to generate a random order number - Nees work
Label(self,text = "Random Order Number:"
).grid(row=3,column=2,sticky=W)
#self.Random_ent = RandomNumber(random.randrange(100))
# Create a label for Starter Menue
Label(self,
text = "Select from starter Menue #R55:"
).grid(row = 7, column = 0, sticky = W)
# create variable for single starter menue item
self.Starter_menue = StringVar()
#create starter menue radio buttons
#Starter_menue = ["Prawn and Muchroom cocktail", "9 Oysters", "Goats cheese"]
#column = 0
#for part in Starter_menue:
# Radiobutton(self,
# text = part,
# variable = self.Starter_menue,
# value = part
# ).grid(row = 9, column = column, sticky = W)
#column += 1
#create radion for Starter item menue 1
Radiobutton(self,text="Prawn and Mushroom",
variable = self.Starter.menue, value = 55, command =self.determine_order
).grid(row=9, column =1, sticky = W)
# Create a label for Starter Menue
Label(self,
text = "Select from Mains Menue #R100:"
).grid(row = 10, column = 0, sticky = W)
# create variable for single mains menue item
self.Mains_menue = StringVar()
#create main course radio buttons
Mains_menue = ["250g Fillet", "Beef Schnitzel", "Chicken", "Quails", "Ravioli", "Genooch"]
column = 0
for part in Mains_menue:
Radiobutton(self,
text = part,
variable = self.Mains_menue,
value = part
).grid(row = 11, column = column, sticky = W)
column += 1
#MENU items to choose from
#I'll do one example with a check button
#the salads
Label(self,text = "Select from Salads"
).grid(row=4,column=0,sticky=W)
self.has_green = BooleanVar()
self.has_blue = BooleanVar()
self.has_ceaser = BooleanVar()
#the greens
Checkbutton(self, text="Greens",
variable=self.has_green
).grid(row=5,column=0,sticky=W)
#the blue salad
Checkbutton(self, text="Blue",
variable=self.has_blue
).grid(row=5,column=1,sticky=W)
#The Ceaser Salad
Checkbutton(self,text="Ceaser Salad",
variable=self.has_ceaser
).grid(row=5,column=2,sticky=W)
#Place the order
Button(self,text = "Place the Order",command = self.determine_order, bg="gold").grid(row = 14, column = 0, sticky = W)
#The display area
self.txt_order = Text(self, width = 75, height = 5, wrap = WORD)
self.txt_order.grid(row = 15, column = 0, columnspan = 4)
def RandomNumber():
RandomNumber = random.randrange(100)
def determine_order(self):
#Get all the information from the GUI
totalprice = 0
totalMain =0
totalStarter =0
grandTotal = totalMain + totalStarter + totalprice
greensaladprice=40
bluesaladprice=40
ceasersaladprice=40
CustomerName =self.CustomerName_ent.get()
Telephone=self.Telephone_ent.get()
Starter_menue = self.Starter_menue.get()
Starter1 = 55
Starter2= 55
Starter3=55
#Check if and which salads are selected
if self.has_green.get():
totalprice = totalprice + greensaladprice
if self.has_blue.get():
totalprice = totalprice + bluesaladprice
if self.has_ceaser.get():
totalprice = totalprice + ceasersaladprice
#Check if and which Starters are selected
if self.Starter_menue(0):
totalStarter = totalStarter + Starter1
if self.Starter_menue(1):
totalStarter = totalStarter + Starter2
if self.Starter.get():
totalStarter = totalStarter + Starter3
#Display the total
self.txt_order.delete(0.0,END)
self.txt_order.insert(0.0,float(grandTotal))
# Add the name -Needs work
self.txt_order.insert(100.50,CustomerName)
#Add telephone number - Needs Work
self.txt_order.insert(0.0,Telephone)
def main():
root = Tk()
root.title("Example - menu 1")
app = App(root)
root.mainloop()
main()
First off, are you missing some code in your example? possibly a Starter initialisation in the App class?
I get a traceback if I try to run:
Traceback (most recent call last):
File "test.py", line 165, in <module>
main()
File "test.py", line 160, in main
app = App(root)
File "test.py", line 10, in __init__
self.create_widgets()
File "test.py", line 57, in create_widgets
variable = self.Starter.menue, value = 55, command =self.determine_order
AttributeError: App instance has no attribute 'Starter'

Categories