I am trying to save progress as a text file. I've tried pickle but it didn't work.
Here's the code; I want to ask at the start if they want to load or start a new game and at any point of the guessing process if they want to save their progress.
# Username and password system to get into the puzzle
Username = []
Password = []
while Username != "Username":
Username = input("Please enter your username: ")
while Password != "Password":
Password = input("Please enter your password: ")
#Import Modules
import tkinter as tkr
import string
import random
import os
import time
from collections import OrderedDict
while True:
#Define Root From tkinter
root = tkr.Tk()
root.configure(background="white")
root.configure(highlightbackground="grey")
root.iconbitmap("PuzzleIcon.ico")
#Inputs for title etc...
Title = input("Please enter the Title of your puzzle: ")
Phrase = input("Please enter the phrase you would like to be encoded: ").upper()
giveaways = str(input("Please enter the letters you want to giveaway with no spaces: ")).upper()
giveaways = giveaways + " "
giveaways = "".join(OrderedDict.fromkeys(giveaways))
root.title(Title)
#Define alphabet and numbers
Alphabet = list(string.ascii_uppercase)
Numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]
random.shuffle(Numbers)
# Specifies the numbers to put under the phrase
AlphabetNumbersToDisplay = []
Numbers.append(" ")
Alphabet.append(" ")
for letter in Phrase:
n = 0
found = False
while n < len(Alphabet) and found == False:
if letter == Alphabet[n]:
AlphabetNumbersToDisplay.append(Numbers[n])
found = True
n = n + 1
# Defines the tkinter window
def tkinterDisplay():
for i in range (0, len(Alphabet)):
tkr.Label(root, text=Alphabet[i], fg="black", bg="white", width=3).grid(row=0, column=i)
for i in range (0, len(Numbers)):
if Alphabet[i] in giveaways:
tkr.Label(root, text=Numbers[i], fg="black", bg="white", width=3).grid(row=1, column=i)
else:
tkr.Label(root, text= "__", fg="black", bg="white", width=3).grid(row=1, column=i)
tkr.Label(root, text=" ", fg = "white",bg="white").grid(row=2)
for i in range(0, len(Phrase)):
if Phrase[i] in giveaways:
tkr.Label(root, text=Phrase[i], fg= "black", bg="white", width = 3).grid(row = 3, column =i)
else:
tkr.Label(root, text="__", fg= "black", bg="white", width = 3).grid(row = 3, column =i)
for i in range(0, len(AlphabetNumbersToDisplay)):
tkr.Label(root, text=AlphabetNumbersToDisplay[i], fg= "black", bg="white", width = 3).grid(row = 4, column =i)
winMessage = "Well done! You Won!".upper()
for i in range(0, len(winMessage)):
if len(giveaways) == 27:
tkr.Label(root, text=" ", fg = "white",bg="white").grid(row=5)
tkr.Label(root, text=winMessage[i], fg="red", bg="white", width = 3).grid(row = 6, column=i)
# Guessing system for the program
def Guessing():
tkinterDisplay()
while True:
try:
GuessNum = int(input("Please enter the number of your guess: "))
break
except ValueError:
print("Your answer must be a number!")
while True:
try:
GuessLetter = str(input("Please enter the letter you want to guess: ")).upper()
break
except ValueError:
print("Your answer must be a letter!")
foundMatch = False
for i in range(0, len(Alphabet)):
if Alphabet[i] == GuessLetter and Numbers[i] == GuessNum:
global giveaways
foundMatch = True
giveaways = giveaways + Alphabet[i]
if foundMatch == False:
print("They do not match, try again!")
elif foundMatch == True and len(giveaways) < 27:
print("Well done! Keep going!")
while len(giveaways) < 27:
Guessing()
tkinterDisplay()
def Clear():
os.system("cls")
if len(giveaways) == 27:
tkinterDisplay()
print("Well done! You won! The phrase you guessed was: " + Phrase)
Restart = input("Would you like to play again? (Y/N): ").upper()
if Restart == "N":
break
elif Restart == "Y":
print("Restarting Puzzle...")
time.sleep(.1500)
root.destroy()
Clear()
continue
root.mainloop()
This is a very broad question. Building a 'save' option may well be as much work as the rest of the game again. You need to consider the following:
What data is needed to fully define the state of the game at any given point (this is what goes in the text file)
What logic is needed to reconstruct a game in a saved state (you'll need to write new code for this)
How and when to give your users the chance to load/save (this affects the gameplay experience)
Related
I created a password generator, which creates random passwords out of symbols, numbers and characters. There I have an input, where the user must enter a value and it has to be numeric. So I tried to solve this with elif. But, even when expected number (int) is entered, the loop is still stuck at elif. Here my code:
def PasswordGenerationFunc():
password = None
passwordLength = inputPasswordLength.get()
userName = inputUsername.get()
if len(passwordLength) == 0:
ResultDisplay.configure(text="Length of password is mandatory.", fg="red")
elif type(passwordLength) != int:
ResultDisplay.configure(text="Only digits are allowed." + passwordLength, fg="red")
else:
passwordLength = int(passwordLength)
if passwordLength > maxPasswordLength:
ResultDisplay.configure(text="The limit of password length are 20 characters.", fg="red")
else:
if userName != "":
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password for " + userName + " is:\n" + password, fg="white")
else:
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password is: \n" + password, fg="white")
In
ResultDisplay.configure(text="Only digits are allowed." + passwordLength, fg="red")
I print out passwordLength to check if wrong values were passed, but was not the case. I am so into the loop, I might ignoring some logic.
Expected behaviour:
User enters letters, loop stops at elif. User enters digits, loop enters else condition.
Now:
User enters digits, loop still stops at elif.
Here my full code, so you might understand it better:
# This is a small tool to generate passwords
# IMPORTS
from datetime import datetime
import random
from tkinter import *
# VARIABLES
date = datetime.now()
dateFormat = str(date.strftime("%d-%m-%Y %H:%M:%S"))
lowerCase = "abcdefghijklmnopqrstuvwxyz"
upperCase = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
numbers = "0123456789"
symbols = "!?%&##+*"
passwordConstructor = lowerCase + upperCase + numbers + symbols
maxPasswordLength: int = 20
bgColor_1 = "black"
# MAKE OUTPUT SELECTABLE
# GENERATE PASSWORD FUNCTION
def PasswordGenerationFunc():
password = None
passwordLength = inputPasswordLength.get()
userName = inputUsername.get()
if len(passwordLength) == 0:
ResultDisplay.configure(text="Length of password is mandatory.", fg="red")
#elif type(passwordLength) != int:
elif isinstance(passwordLength, int):
ResultDisplay.configure(text="Only digits are allowed.", fg="red")
else:
passwordLength = int(passwordLength)
if passwordLength > maxPasswordLength:
ResultDisplay.configure(text="The limit of password length are 20 characters.", fg="red")
else:
if userName != "":
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password for " + userName + " is:\n" + password, fg="white")
else:
password = "".join([random.choice(passwordConstructor) for i in range(passwordLength)])
ResultDisplay.configure(text="Generated password is: \n" + password, fg="white")
# SCREEN
screen = Tk()
screen.geometry("450x400")
screen.configure(bg="black")
screen.title("PASSWORD GENERATOR")
# TITLE
Title = Label(screen, text="PASSWORD GENERATOR", font=("Arial Bold", 18), fg="green")
Title.configure(bg="black")
Title.pack(pady=20)
# MAIN FRAME
MainFrame = Frame(screen)
MainFrame.configure(bg="black")
MainFrame.pack(pady=5)
# INPUT USERNAME
usernameLabel = Label(MainFrame, text="Please enter username:", font=("Arial Bold", 14))
usernameLabel.configure(bg="black")
usernameLabel.pack()
inputUsername = Entry(MainFrame, font=("Arial Bold", 12))
inputUsername.pack()
# INPUT PASSWORD LENGTH
passwordLengthLabel = Label(MainFrame, text="Please enter length of password:", font=("Arial Bold", 14))
passwordLengthLabel.configure(bg="black")
passwordLengthLabel.pack()
inputPasswordLength = Entry(MainFrame, font=("Arial Bold", 12))
inputPasswordLength.pack()
# GENERATE BUTTON
GenerateBtn = Button(MainFrame, text="GENERATE", font=("Arial", 14), command=PasswordGenerationFunc, bg="black")
GenerateBtn.pack(pady=10)
# DISPLAY RESULT
ResultDisplay = Label(MainFrame, text="", font=("Arial", 14))
ResultDisplay.configure(bg="black")
ResultDisplay.pack(pady=15)
# COPY TO CLIPBOARD BUTTON
#CopyBtn = Button(MainFrame, text="COPY", font=("Arial", 14), bg="black")
#CopyBtn.clipboard_append(password)
#CopyBtn.pack(pady=10)
# WINDOW
screen.mainloop()
First, convert the input to int.
try:
passwordLength = int(input("Your message "))
except ValueError:
print(f"Input is not a valid integer. Please try again.")
Modify the if conditions for an integer input as follows:
if passwordLength == 0:
pass # your output here
else:
pass # your logic to generate a password
To compare objects and its datatype use isinstance(object, type):
isinstance(3, int) ===> True
isinstance(3, str) ===> False
previous issue was resolved thanks to you guys can anyone also help me with the validation like if a person clicks check with empty field it prints a message in entry2 like "Field cannot be empty" .Adding code for reference .
from tkinter import *
from tkinter.messagebox import *
import random
root = Tk()
root.title('Number Guessing Game E-project')
root.geometry('500x500')
label1 = Label(root, text= "WELCOME TO NUMBER GUESSING GAME",fg='Maroon',font= ('bold',17))
label2 = Label(root, text= "Enter your guess between 0-999:",font=('Italics',15), fg='Maroon')
label1.grid(row=1 , column=0 ,ipadx=20,pady=10)
label2.grid(row=4 , column=0 ,ipadx=10,pady=10)
player1 = StringVar(root,value="Generate A Random Number First")
entry1 = Entry(root,textvariable=player1,width=30,bd=4)
entry2 = Entry(root,width=30,bd=4)
entry1.grid(row =12 , column= 0 ,ipadx=10,pady=10)
entry2.grid(row =13, column= 0 ,ipadx=10,pady=10)
attempts = 10
chances = StringVar()
chances.set("10 Attempts Remaining")
label4 = Label(root,textvariable=chances,font='Italics')
label4.grid(row=7,column=0 ,ipadx=10,pady=10)
def clear_the_screen():
entry1.delete(0,END)
def random_num_generate():
global random_number , user_guess
random_number = random.randint(0,999)
clear_the_screen()
def player_input():
try:
user_guess = int(entry1.get())
winning_logic(random_number,user_guess)
except ValueError:
entry2.insert(0,"Enter integers only!")
result3 = 'Enter integers only!'
entry2.delete(0, END)
entry2.insert(0, result3)
chances.set(f'{attempts} attempts remaining')
clear_the_screen()
def winning_logic(random_no,player_guess):
global attempts
global chances
attempts -= 1
if attempts < 1:
a = (f'You are out of attempts \n Try again')
showinfo("Sorry", a)
root.destroy()
elif player_guess == random_no:
result1 = 'Bravo! Success!'
entry2.delete(0, END)
entry2.insert(0,result1)
chances.set(f'You Win!')
win = (f'Congrats! You have guessed the correct number !')
showinfo(f'Number Guessing Game', win)
response = askquestion('Number Guessing Game', 'Did you like the game?')
if response == 'yes':
showinfo('Number Guessing Game', "That's Great!!")
else:
showinfo('Number Guessing Game',"So Sad!")
root.destroy()
elif player_guess < random_no and player_guess < 1000:
result2 = 'Guess Higher!'
entry2.delete(0,END)
entry2.insert(0, result2)
chances.set(f'Wrong! {attempts} attempts remaining')
clear_the_screen()
elif player_guess > random_no and player_guess < 1000:
result3 = 'Guess Lower!'
entry2.delete(0,END)
entry2.insert(0, result3)
chances.set(f'Wrong! {attempts} attempts remaining')
clear_the_screen()
elif player_guess > 999:
result3 = 'Invalid Number!'
entry2.delete(0, END)
entry2.insert(0, result3)
chances.set(f'Invalid Number! {attempts} attempts remaining')
clear_the_screen()
button1 = Button(root, text='Generate Random No',fg='white',bg='brown',command=random_num_generate)
button1.grid(row=9, column=0,ipadx=20,pady=8)
button2 = Button(root, text='Clear',fg='white',bg='brown',command=clear_the_screen)
button2.grid(row=18, column=0,ipadx=73,pady=10)
button3 = Button(root, text='Check',fg='white',bg='brown',command=player_input)
button3.grid(row=20, column=0,ipadx=70,pady=8)
root.mainloop()
You can check whether the input is empty in the except block inside player_input():
def player_input():
user_guess = entry1.get()
try:
user_guess = int(user_guess)
winning_logic(random_number, user_guess)
except ValueError:
if user_guess == '':
result3 = 'Field cannot be empty!'
else:
result3 = 'Enter integer only!'
entry2.delete(0, END)
entry2.insert(0, result3)
chances.set(f'{attempts} attempts remaining')
clear_the_screen()
I am new to python and I've been trying to code a simple hangman game using tkinter. However my tkinter window does not appear when I run the program, like it should. It appears only after the game has ended. i am really confused and cannot for the life of me figure out what is wrong.
Here is my code:
from tkinter import*
from tkinter import messagebox
import random
main = Tk()
main.title("Hangman game")
main.geometry("800x700+120+100")
#-----------------------------------------------------------1
pokusy = 5
spatne_pis = ""
slovo = ""
def vybrat_slovo(slovo):
slovo = random.choice(open("slova_python.txt","r").read().split())
return slovo
spravne_pis = ""
neuhadle = ""
def ukazani(spatne_pis, spravne_pis, slovo):
letters = ""
for letter in spatne_pis:
letters = letters + letter
pism_disp.set(" ".join(letters))
print()
neuhadle = "_"*len(slovo)
for i in range(len(slovo)):
if slovo[i] in spravne_pis:
neuhadle = neuhadle[:i] + slovo[i] + neuhadle[i+1:]
slovo_disp.set(" ".join(neuhadle))
return neuhadle
#----------------------------------------------------------------2
vrchni=Frame(main,width=800,height=50,bd=2,relief="raise")
vrchni.pack(side=TOP,fill=BOTH)
hl_ramec=Frame(main,width=800,height=200,relief="raise")
hl_ramec.pack(side=TOP,fill=BOTH)
klavesnice=LabelFrame(main,text='keys',width=800,height=300,bd=2,relief="raise")
klavesnice.pack(side=TOP,fill=BOTH)
mezera=Frame(main,width=800,height=40,relief="raise")
mezera.pack(side=TOP,fill=BOTH)
dolni=LabelFrame(main,text='comments',width=800,height=100,bd=2,relief="raise")
dolni.pack(side=TOP,fill=BOTH)
hlaska = StringVar()
koment_lb = Label(dolni, textvariable = hlaska, font = ("Arial 22")).grid(padx=90, pady=20)
pomoc_rm=Frame(hl_ramec,width=400,height=300,relief='raise')
pomoc_rm.pack(side=LEFT)
obrazek_ramec=LabelFrame(hl_ramec,text='Hangman - picture',width=400,height=300,bd=2,relief='raise')
obrazek_ramec.pack(side=RIGHT)
status_rm=LabelFrame(pomoc_rm,text='status',width=350,height=80, relief='raise', padx = 10, pady=7)
status_rm.pack(side=TOP)
zbyvajici = IntVar()
pocet_lb = Label(status_rm, textvariable = zbyvajici, font=("Arial 22"))
pocet_lb.pack(side=RIGHT)
zbyvajici = pokusy - len(spatne_pis)
text_lb = Label(status_rm, text="Number of remaining guesses: ", font=("Arial 16"))
text_lb.pack(side=LEFT)
slovo_rm=LabelFrame(pomoc_rm,text='word',width=350,height=100,relief='raise')
slovo_rm.pack(side=TOP)
slovo_disp = StringVar()
slovo_lb = Label(slovo_rm, textvariable = slovo_disp, font = ("Arial 30")).grid(padx=30, pady=7)
zadane_rm=LabelFrame(pomoc_rm,text='wrong entered keys',width=350,height=80,relief='raise')
zadane_rm.pack(side=TOP)
pism_disp = StringVar()
pismena_lb = Label(zadane_rm, textvariable = pism_disp, font = ("Arial 16")).grid(padx=120, pady=15)
#vytvoření malé klávesnice pro uživatele
buttons = [] #seznam jednotlivých kláves
buttons = [
'q','w','e','r','t','y','u','i','o','p',
'a','s','d','f','g','h','j','k','l',
'z','x','c','v','b','n','m'
]
radek=3
sloupec=0
for button in buttons:
command=lambda x=button: select(x)
if button!='Space':
Button(klavesnice,text=button,width=5,font=("arial",14,"bold"),bg='powder blue',command=command,padx=3.5,pady=3.5,bd=5).grid(row=radek,column=sloupec)
if button=='Space':
Button(klavesnice,text=button,command=command).grid(row=5,column=sloupec)
sloupec+=1
if sloupec>9 and radek==3:
sloupec=0
radek+=1
if sloupec>8 and radek==4:
sloupec=0
radek+=1
#---------------------------------------------------------3
uhadle_pis = ""
def hadani(uhadle_pis):
while True:
hlaska = ("Try guessing a letter.")
zadane = input()
zadane = zadane.lower()
if len(zadane) != 1:
hlaska = ("Please enter only one letter")
elif zadane in uhadle_pis:
hlaska = ("You have already guessed that letter, try guessing again. :)")
elif zadane not in "abcdefghijklmnopqrstuvwxyz":
hlaska = ("Please enter a letter of the english alphabet. Entering other characters will not work.")
else:
return zadane
def hrat_znovu():
print('Do you want to play again? (yes or no)')
return input().lower().startswith('y')
szn = ""
konec_hry = False
slovo = vybrat_slovo(slovo)
while True:
ukazani(spatne_pis,spravne_pis,slovo)
zadane = hadani(spatne_pis + spravne_pis)
if zadane in slovo:
spravne_pis = spravne_pis + zadane
uhadnuto = True
for i in range(len(slovo)):
if slovo[i] not in spravne_pis:
uhadnuto = False
break
if uhadnuto:
konec_hry = True
hlaska = ("Great job! You have succesfully guessed the word! The word was: ",slovo)
else:
spatne_pis = spatne_pis + zadane
if len(spatne_pis) == pokusy:
konec_hry = True
hlaska = ("Sorry, you have been hanged. :(( The word was: ", slovo, ". Try playing again!")
if konec_hry:
if hrat_znovu():
spatne_pis = ""
spravne_pis = ""
konec_hry = False
slovo = vybrat_slovo(slovo)
else:
break
main.mainloop()
The code between the first #--- and second is maybe not important, but i want to include it to be sure. As i said, the tkinter only opens itself if the game has ended and the player does not want to play again. I will be very grateful for any answers :).
def gameloop():
szn = ""
konec_hry = False
slovo = vybrat_slovo(slovo)
while True:
ukazani(spatne_pis, spravne_pis, slovo)
zadane = hadani(spatne_pis + spravne_pis)
if zadane in slovo:
spravne_pis = spravne_pis + zadane
uhadnuto = True
for i in range(len(slovo)):
if slovo[i] not in spravne_pis:
uhadnuto = False
break
if uhadnuto:
konec_hry = True
hlaska = (
"Great job! You have succesfully guessed the word! The word was: ",
slovo)
else:
spatne_pis = spatne_pis + zadane
if len(spatne_pis) == pokusy:
konec_hry = True
hlaska = ("Sorry, you have been hanged. :(( The word was: ", slovo,
". Try playing again!")
if konec_hry:
if hrat_znovu():
spatne_pis = ""
spravne_pis = ""
konec_hry = False
slovo = vybrat_slovo(slovo)
else:
break
main.after(1000,gameloop)
main.mainloop()
#carPark
from tkinter import *
root = Tk()
root.title("OCR's car park program")
frame = Frame(root)
frame.grid(row = 2, column = 0)
def program():
loop = True
while loop:
if len(plateNumber.get()) == 3:
welcome.config(text = "Valid plate number.")
loop = False
elif len(plateNumber.get()) != 3:
welcome.config(text = "Invalid plate number.")
askPlate()
def askPlate():
global plateNumber
plateNumber = Entry(frame)
plateNumber.grid(row = 2, column = 1)
plateNumberLabel = Label(frame, text = "Enter the last 3 digits of your car's plate number: ")
plateNumberLabel.grid(row = 2, column = 0)
checker = Button(root, text = "Click me when you're done.", command = program)
checker.grid(row = 3, column = 0)
try:
plateNumber.delete(END, 0)
except:
pass
welcome = Label(root, text = "Welcome to OCR's car park program.")
welcome.grid(row = 0, column = 0)
price = "2"
pricePay = Button(root, text = "Click me to accept the £" + price + " ticket fee.", command = askPlate)
pricePay.grid(row = 1, column = 0)
root.mainloop()
Whenever I enter an input that is equal to the length of 3 it works but when it isn't equal to 3 it just crashes. I don't know why this is happening and would really appreciate some help.
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().