checking if a variable is an integer or not on python - python

I am making a maths test using tkinter. I have 4 entries to allow the user to input the answers of questions. the answers must be in integer format if not it will give a long error. I wanted my program to check if the inputted value is an integer or not.and then if it is not an integer open up a message box telling the user to check the answers.
here is my code: (it's a long code because I didn't know how to shorten it, I'm not a programmer)
from tkinter import*
from tkinter import messagebox
from random import*
n1= randint(1,6)
n2= randint(1,9)
ques1 = n1, "x", n2, "="
c1= n1*n2
n1= randint(8,15)
n2= randint(1,7)
ques2 = n1, "-", n2, "="
c2= n1-n2
n1= randint(1,10)
n2= randint(5,15)
ques3 = n1, "+", n2, "="
c3= n1+n2
n1= randint(5,12)
n2= randint(1,10)
ques4 = n1, "x", n2, "="
c4= n1*n2
#window
window = Tk()
window.geometry("280x450")
window.title("quiz")
window.configure(background='yellow')
def checkthrough():
if ans1.get() == '':
messagebox.showinfo("error", "check again ")
elif ans2.get() == '':
messagebox.showinfo("error", "check again ")
elif ans3.get() == '':
messagebox.showinfo("error", "check again ")
elif ans4.get() == '':
messagebox.showinfo("error", "check again ")
else:
save()
#this is where i tried to check if it's an integer or not
try:
ans1 == int()
except:
messagebox.showinfo("error", "check again ")
def save():
score = 0
if c1==int(ans1.get()):
score= score + 1
if c2==int(ans2.get()):
score = score+1
if c3==int(ans3.get()):
score = score+1
if c4==int(ans4.get()):
score = score+1
fscore.set(score)
def savetofile():
result = result ="\n "+ namestudent.get() + " " + fscore.get()+"/4"
messagebox.showinfo("results", "your results been saved successfuly")
if int(year.get())==1:
f = open('results C1.txt', 'a')
f.write(result)
f.close()
if int(year.get())==2:
f = open('results C2.txt', 'a')
f.write(result)
f.close()
if int(year.get())==3:
f = open('results C3.txt', 'a')
f.write(result)
f.close()
#frame
frame = Frame(window)
frame.columnconfigure(0, weight=1)
frame.rowconfigure(0, weight=1)
#variables
namestudent = StringVar()
ans1 = StringVar()
ans2 = StringVar()
ans3 = StringVar()
ans4 = StringVar()
fscore = StringVar()
year = StringVar()
#labels
name = Label(window, text = "type your name:")
name.grid(row= 6, column = 0)
yr = Label(window, text = "type your class:")
yr.grid(row= 7, column = 0)
q1 = Label(window,text = ques1, height = 3, bg = 'yellow')
q1.grid(row = 1,column=0)
q2 = Label(window,text = ques2, height = 3, bg = 'yellow')
q2.grid(row = 2,column=0)
q3 = Label(window,text = ques3, height = 3, bg = 'yellow')
q3.grid(row = 3,column=0)
q4 = Label(window,text = ques4, height = 3, bg = 'yellow')
q4.grid(row = 4,column=0)
#entrys
name_entry= Entry(window, textvariable= namestudent)
name_entry.grid(row = 6, column=1)
yr_entry= Entry(window, textvariable= year)
yr_entry.grid(row = 7, column=1)
q1_entry = Entry(window, width = 6, textvariable = ans1)
q1_entry.grid(row = 1,column=1)
q2_entry = Entry(window, width = 6, textvariable = ans2)
q2_entry.grid(row = 2,column=1)
q3_entry = Entry(window, width = 6, textvariable = ans3)
q3_entry.grid(row = 3,column=1)
q4_entry = Entry(window, width = 6, textvariable = ans4)
q4_entry.grid(row = 4,column=1)
#buttons
finish = Button(window, width = 5, text = "finish",command= checkthrough)
finish.grid(row = 5,column=0)
finalS_label = Label(window, textvariable=fscore)
finalS_label.grid(row=5, column=1)
saving = Button(window, width = 5, text = "save", command= savetofile)
saving.grid(row= 8, column=0)
window.mainloop()
I read some other post about the same question and I tried to use their answers in my code but still I'm getting the same error.
thanks.

In order to check if a string is integer-convertible, just try converting it and check for exceptions.
try:
integer_result = int(string_result)
except ValueError:
print("not a valid integer")
else:
print("value is", integer_result)
To do this in your case, you want to extract the values from ans1 &c. beforehand, then pass the raw strings to int().

Related

How do I update my answer message coding?

I am doing a coding where I need to program different math flashcards and the user has to answer them. But when answering them, the message keeps saying the same number and not updating the new numbers that it is supposed to get.
from tkinter import messagebox
from random import randint
def clicked():
messagebox.showinfo('Rules of the Game', '1. You are going to be provided with basic arithmetic (Adding, Subtracting, Multiplying)'
'\n2. You are going to answer them'
'\n3. Based on the answer you gave, it will keep track of the correct and incorrect answers including how many in total you have answered')
root = Tk()
root.title('Math Flash Cards')
root.geometry('900x500')
Title = Label(root, text="Title", font=('Arial', 30))
Title.grid(row = 0, column = 4)
Rule_btn = Button(root, text="Click Here for Rules", font=('Arial'), command=clicked)
Rule_btn.grid(row = 3, column = 4)
#Create random flashcard numbers
def math_random():
global nums
number_1 = randint(1,10)
number_2 = randint(1,10)
add_1.configure(text = number_1)
add_2.configure(text = number_2)
def answer_add():
answers = number_1 + number_2
if int(add_ans.get()) == answers:
response = 'Correct ' + str(number_1) + ' + ' + str(number_2) + ' = ' + str(answers)
elif int(add_ans.get()) != answers:
response = 'Wrong! ' + str(number_1) + ' - ' + str(number_2) + ' = ' + str(answers)
answer_message.config(text = response)
add_ans.delete(0, 'end')
math_random()
global nums
number_1 = randint(1,10)
number_2 = randint(1,10)
global add_1
global add_2
add_1 = Label(root, text='+', font=('Arial', 20))
add_2 = Label(root, text='+', font=('Arial', 20))
math_operator = Label(root, text='+', font=('Arial', 20))
add_1.grid(row = 5, column = 3)
math_operator.grid(row = 5, column = 4)
add_2.grid(row = 5, column = 5)
add_1.configure(text = number_1)
add_2.configure(text = number_2)
global add_ans
add_ans = Entry(root, font = ('Arial', 14))
add_ans.grid(row = 7, column = 4)
add_ans_btn = Button(root, text ='Click', font = ('Arial'), command= answer_add)
add_ans_btn.grid(row = 7, column = 5)
global answer_message
answer_message = Label(root, text='Type you answer with the provided space above', font=('Arial'))
answer_message.grid(row = 10, column = 4)
What should I do to make it update? I kept making changes to the code, but it is not changing when the numbers are changing.

First tkinter project ,trying to find a way to make my tkinter buttons change boolean values for future if statements

I couldnt seem to find a way to make my program realise that ive selected a button, so i changed the function of the celcius to farenheit to try to make it change a boolean value to determine what conversion the program is doing
def celcius_to_farenheit(_event = None):
c_to_f = True
f_to_c = False
the idea being later i can use if statments later in the end result function to find what conversion its doing and display results in the status bar
def end_result():
if c_to_f == True:
converted_temperature = (valid_temperature * 9/5) + 32
label_status.configure(text = converted_temperature, fg = "Orange")
currently i seem to have functions running without me pressing buttons as well, when start the program it immediatly goes to the error message ive created for input muct be numeric even if i havent pressed the celcius to farenheit button.
Any help regarding how to propely have my celcius to farenheit and farenheit to celcius buttons confirm its a float and change a value to use for determining which calculation its using would be helpfull. Knowing why the error message comes up automatically is a bonus.
Below is my code thank you for your time and help.
import sys
from tkinter import *
from tkinter.tix import *
c_to_f = True
def clear_reset(_event = None):
entry_temperature.delete(0, END)
label_status.configure(text = "All data cleared", fg = "Orange")
def end_program(_event = None):
sys.exit()
def convert_temp(_event = None):
try:
valid_temperature = float(entry_temperature.get())
except:
label_status.configure(text = "Input must be numeric", fg = "Orange")
def end_result():
if c_to_f == True:
converted_temperature = (valid_temperature * 9/5) + 32
label_status.configure(text = converted_temperature, fg = "Orange")
def celcius_to_farenheit(_event = None):
c_to_f = True
f_to_c = False
def farenheit_to_celcius(_event = None):
f_to_c = True
c_to_f = False
window = Tk()
window.geometry("550x200")
window.resizable(False, False)
window.title("Temperature Conversion")
tooltip = Balloon(window)
label_input_Temperature = Label(text = "Temperature",fg = "Green")
label_input_Temperature.grid(row= 0, column=0)
entry_temperature = Entry(window, bg = "light blue" )
entry_temperature.grid(row=0, column=1)
temp_button_c_to_f = Button(window, text = "Celcius to Farenheit", command = celcius_to_farenheit)
temp_button_c_to_f.grid(row = 1, column=0)
window.bind('<Shift-c>', celcius_to_farenheit)
tooltip.bind_widget(temp_button_c_to_f, msg = "Shift + C")
temp_button_f_to_c = Button(window, text = "Farenheit to Celcius")
temp_button_f_to_c.grid(row = 1, column = 1 )
conversion_button = Button(window, text = "Convert", command = convert_temp)
conversion_button.grid(row = 2, column = 0,padx =0 )
window.bind('<Enter>', convert_temp)
tooltip.bind_widget(conversion_button, msg = "Enter")
clear_button = Button(window, text = "Clear", command = clear_reset)
clear_button.grid(row = 2, column = 1)
window.bind('<Control-c>', clear_reset)
tooltip.bind_widget(clear_button, msg = "Ctrl + C")
exit_button = Button(window, text = "Exit")
exit_button.grid(row = 2, column = 2, padx = 20, pady = 20)
window.bind('<Control-x>', end_program)
tooltip.bind_widget(exit_button, msg = "Ctrl + X")
label_status = Label(window, width = 50, borderwidth = 2, relief= RIDGE,bg= "Grey" )
label_status.grid(row = 4, column = 1)
tooltip.bind_widget(label_status, msg = "Displays results / error messages")
label_status.configure(text = "Enter in your temperature and select your conversion", fg = "Orange")
window.mainloop()

Tkinter get() function is not returning anything [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 3 years ago.
I am trying to write a program using a tkinter GUI to calculate a few things. My get() function isn't working and I'm not sure why
from tkinter import *
from math import *
root = Tk()
v = 0
l = 0
w = 0
t1 = 0
t0 = 0
label1 = Label(root, text = "Enter value for length (mm) :").grid(columnspan = 2, sticky = "E")
length = Entry(root).grid(row = 0, column = 2)
label2 = Label(root, text = "Enter value for volume (mm^2) :").grid(columnspan = 2, sticky = "E")
volume = Entry(root).grid(row = 1, column = 2)
label3 = Label(root, text = "Enter value for the thickness of the cylinder (mm) :").grid(columnspan = 2, sticky = "E")
thickness = Entry(root).grid(row = 2, column = 2)
label4 = Label(root, text = "Enter value for starting temperature (K) :").grid(columnspan = 2, sticky = "E")
st_T = Entry(root).grid(row = 3, column = 2)
label5 = Label(root, text = "Enter value for finishing temperature (K) :").grid(columnspan = 2, sticky = "E")
end_T = Entry(root).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]
answer = StringVar()
labelans = Label(root, textvariable = answer).grid(columnspan = 3,)
answer.set("Answer = ")
def area_circle():
global answer
answer = v / l
print(answer)
Button(root, text = "Submit", command = save()).grid(row = 6, column = 0)
root.mainloop()
Obviously there are variables i'm not using yet but im trying to get the first part right first.
For v the error displayed is:
Message='NoneType' object has no attribute 'get'
The Grid geometry manager puts the widgets in a 2-dimensional table.
The master widget is split into a number of rows and columns, and each
“cell” in the resulting table can hold a widget.
What is important Grid() is returning NoneValue
if you are doing like:
length = Entry(root).grid(row = 0, column = 2)
in your variable length you will have NoneValue
you should do it like :
length = Entry(root)
length.grid(row = 0, column = 2)
your code:
label1 = Label(root, text = "Enter value for length (mm) :")
label1.grid(columnspan = 2, sticky = "E")
length = Entry(root)
length.grid(row = 0, column = 2)
label2 = Label(root, text = "Enter value for volume (mm^2) :")
label2.grid(columnspan = 2, sticky = "E")
volume = Entry(root)
volume.grid(row = 1, column = 2)
label3 = Label(root, text = "Enter value for the thickness of the cylinder (mm) :")
label3.grid(columnspan = 2, sticky = "E")
thickness = Entry(root)
thickness.grid(row = 2, column = 2)
label4 = Label(root, text = "Enter value for starting temperature (K) :")
label4.grid(columnspan = 2, sticky = "E")
st_T = Entry(root)
st_T.grid(row = 3, column = 2)
label5 = Label(root, text = "Enter value for finishing temperature (K) :")
label5.grid(columnspan = 2, sticky = "E")
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]
answer = StringVar()
labelans = Label(root, textvariable = answer).grid(columnspan = 3,)
answer.set("Answer = ")
def area_circle():
global answer
answer = v / l
print(answer)
Button(root, text = "Submit", command = save()).grid(row = 6, column = 0)
root.mainloop()
output:
The command argument should be a callback, not the actual call:
Button(root, text="Submit", command=save).grid(row=6, column=0)

'TimeGenerator' object has no attribute 'iso' when self.iso is defined. Shorter version of GUI does not print

this is my program so far.
from tkinter import *
import math
class TimeGenerator:
def __init__(self,master):
frame = Frame(master)
frame.grid()
label_iso = Label(root, text="Isotope A, Element")
label_vol = Label(root, text="Voltage")
label_range = Label(root, text="Charge Range")
entry_iso = Entry(root)
entry_vol = Entry(root)
entry_range = Entry(root)
label_iso.grid(row=0, sticky=E)
label_vol.grid(row=1, sticky=E)
label_range.grid(row=2, sticky=E)
entry_iso.grid(row=0, column=1)
entry_vol.grid(row=1, column=1)
entry_range.grid(row=2,column=1)
button = Button(root, text='Time Range')
button.grid(row=3, columnspan=2)
frame.bind(button,self.calculateTime())
self.iso = entry_iso.get()
self.vol = entry_vol.get()
self.r = entry_range.get()
def calculateTime(self):
x = 5
self.iso.replace(" ", "")
list = []
for e in self.iso.split(","):
list.append(e)
f = open("/Users/LazyLinh/PycharmProjects/mass.mas12.txt", "r")
i = 0
while (i < 40):
header = f.readline()
i += 1
for line in f:
line = line.strip()
columns = line.split()
if (list[0] == columns[5]):
if (list[1] == columns[6]):
self.mass = float(columns[13]) + float(columns[14])
self.r.replace(" ", "")
tup = tuple(int(x) for x in self.r.split(","))
list = []
for q in range(tup[0], tup[1] + 1):
y = x * math.sqrt(self.mass / (2 * q * float(self.vol)))
list.append(y)
i = tup[0]
for time in list:
print(i, ':', time)
i = i + 1
root = Tk()
b = TimeGenerator(root)
root.mainloop()
However, I got an error message saying iso attribute doesn't exist. Meanwhile, the shorter version of the code (just to test things out) below:
from tkinter import *
class TimeGenerator:
def __init__(self, master):
frame = Frame(master)
frame.grid()
label_iso = Label(root, text="Isotope A, Element")
label_vol = Label(root, text="Voltage")
label_range = Label(root, text="Charge Range")
entry_iso = Entry(root)
entry_vol = Entry(root)
entry_range = Entry(root)
label_iso.grid(row=0, sticky=E)
label_vol.grid(row=1, sticky=E)
label_range.grid(row=2, sticky=E)
entry_iso.grid(row=0, column=1)
entry_vol.grid(row=1, column=1)
entry_range.grid(row=2, column=1)
self.iso = entry_iso.get()
self.vol = entry_vol.get()
self.r = entry_range.get()
button = Button(root, text='Time Range')
button.grid(row=3, columnspan=2)
frame.bind(button, self.calculateTime())
def calculateTime(self):
self.iso.replace(" ", "")
list = []
for e in self.iso.split(","):
list.append(e)
f = open("/Users/LazyLinh/PycharmProjects/mass.mas12.txt", "r")
i = 0
while i < 40:
header = f.readline()
i += 1
for line in f:
line = line.strip()
columns = line.split()
if (list[0] == columns[5]):
if (list[1] == columns[6]):
self.mass = float(columns[13]) + float(columns[14])
self.r.replace(" ", "")
self.r.replace("(", "")
self.r.replace(")", "")
print(self.r)
root = Tk()
b = TimeGenerator(root)
root.mainloop()
There is no 'no attribute' errors, meaning self.r does create the attribute 'r'. But still, nothing gets printed in the console, and I can't see why. Can you please help me out?
P/S: I just started python a couple of days ago, so even if there's some very obvious mistakes, they might not be obvious to me, so please be kind :)
This line is wrong:
frame.bind(button,self.calculateTime())
Instead, try:
frame.bind(button,self.calculateTime)
In the first instance, you invoke calculateTime and pass the resulting value to bind. In the second instance, you pass a reference to the function itself to bind.

finding & returning specific line from files in python with tkinter

i am a newbie in python, and i am trying to code a comparison tool and i used tkinter in python 2.7. my gui seems to work fine, but i cannot find the line containing the 'key' to return (even if i use correct key). hoping for your help.
import Tkinter as tk
from Tkinter import *
import os
import tkFont
result = ""
key = ""
def clear():
var4.set("Results...")
entry.set("")
def process():
key = entered.get()
if len(key) == 5 or len(key) == 6:
result = look_up()
var4.set(result)
else:
result = 'Invalid Entry, please enter 5-6 alphanumeric characters... !'
var4.set(result)
def look_up():
file = "compared.txt"
fh = open(file, 'r')
key = pdbCode.get()
lines = fh.readlines()
for line in lines:
#just trying to return a single line first to check
if line.strip().startswith(key):
#a, b, c, d = line.split("::")
#print "For item : " + str(a)
#print "description1 : " + str(b)
#print "description2 : " + str(c)
#print "value : " + str(c)
return line
else:
return "Code not in file..."
root = Tk()
root.title('Comparisson')
root.geometry('550x550+200+200')
entry = StringVar()
entered = Entry(root,textvariable = entry, width = 15)
entered.pack()
button1 = Button(root, text='COMPARE', width = 10, pady = 5, command = process)
button1.pack()
var4 = StringVar()
label4 = Label( root, textvariable=var4, pady = 45)
var4.set("Result here...")
label4.pack()
button2 = Button(root, text='CLEAR ALL', width = 10, command = clear)
button2.pack()
button3 = Button(root, text='QUIT', width = 10, command = root.destroy)
button3.pack()
root.resizable(0, 0)
root.mainloop()

Categories