Assign variable to radiobutton Tkinter - python

I have this code which asks user to select one of the choices. I used radiobuttons. After the user select his choice, the choice will be use another if statement. I already assigned the choice's variable as variable = specialistchoose. But when I use the specialistchoose or specialistchoose.get(), it does not work. Can anyone help?
specialistchoose = IntVar()
r1 = Radiobutton (f2, text = "Cardiology", variable = specialistchoose, value = 1, command = command_r1 )
r1.grid(row = 4, column = 0, stick = W)
r2 = Radiobutton (f2, text = "Gastroenterology", variable = specialistchoose, value = 2, command = command_r2)
r2.grid(row = 4, column = 1,stick = W )
r3 = Radiobutton (f2, text = "Dermatology", variable = specialistchoose, value = 3, command = command_r3)
r3.grid (row = 4, column = 2,stick = W )
r4 = Radiobutton (f2, text = "Psychiatry", variable = specialistchoose, value = 4, command = command_r4)
r4.grid (row = 5, column = 0,stick = W )
r5 = Radiobutton (f2, text = "Dentist", variable = specialistchoose, value = 5, command = command_r5)
r5.grid(row = 5, column = 1,stick = W )
f2.place(relx = 0.01, rely = 0.125, anchor = NW)
Label(f1, text = "Specialist").place(relx = .06, rely = 0.125, anchor = W)
f1.grid(stick = W)
if specialistchoose.get() == "Cardiology":
file = open ("test2.txt", "w")
file.write ("Specialist : Cardiology")
file.close()
elif specialistchoose.get() == "Gastroenterology":
file = open ("test2.txt", "w")
file.write ("Specialist : Gastroenterology")
file.close()
elif specialistchoose.get() == "Dermatology":
file = open ("test2.txt", "w")
file.write ("Specialist : Dermatology")
file.close()
elif specialistchoose.get() == "Psychiatry":
file = open ("test2.txt", "w")
file.write("Specialist : Psychiatry")
file.close()
elif specialistchoose.get() == "Dentist":
file = open ("test2.txt", "w")
file.write("Specialist : Dentist")
file.close()
note : this is just the sample of a longer code.

Since you are get()ting their values only right after they created, you'll get only their initial value and nothing more.
Try to get their value using command, or another button.
No idea what do you have under command_rXs but you should split those if's and put under respective commands.
Also, since your variables are IntVar() and you'll be getting value which will be between 1 and 5 inclusive since you assigned as such.
def command_r1():
with open('test2.txt', 'w') as file:
file.write ("Specialist : Cardiology")
def command_r2():
with open('test2.txt', 'w') as file:
file.write ("Specialist : Gastroenterology")
#etc...
or create a button, when that's clicked it'll get the value and does all those if-else things.
def external_button_callback():
radioValue = specialistchoose.get()
if radioValue == 1:
with open('test2.txt', 'w') as file:
file.write ("Specialist : Cardiology")
#etc...
btn = Button(f2, text= "Get Value" command = external_button_callback)
btn.grid(row=6, column=0)
Another little thing is, when using files, it is better to use with statement since it handles closing automatically when you move out of scope and you don't need to worry about closing everytime.
And everytime you change value, that txt file will be created from scratch since you open it on w mode. I don't know if that's what you wanted or not but wanted to give a heads up.

The value of radiobutton variable has nothing to do with its text. You declared the variable specialistchoose to be IntVar so it will be some int.
if specialistchoose.get() == "Cardiology": will never be True
Yesterday i answered your question on a very same topic here:Gray out a frame after clicking a radiobutton Tkinter
If you alter the func to something like this:
def func():
print specialistchoose.get()
You will be able to see what values each radiobutton gets when it is pressed.
From there you can make a condition if they are pressed or not.

Related

storing output text in a tkinter textbox

im looking to output a list of text to both a text file as well as a tkinter textbox. Currently I have it working to print to a text file being held in the same folder. I would like this same list to be printed on screen into the outputToScreen textbox
From my research I think I am meant to use .insert(index , text) but I can not get this method to work. I have also seen some old code using a .set function but when I tried this I came across an error saying that textbox's don't have that method
#file -> gui.py
# IMPORT tkinter for GUI creation and import scripts for functions
from tkinter import *
from tkinter.ttk import *
import scripts
import customtkinter
windowDim = str(750)+'x'+str(600)
window = customtkinter.CTk()
window.title("INFO GENERATOR")
window.geometry(windowDim)
window.resizable(True, True)
# Modes: system (default), light, dark
customtkinter.set_appearance_mode("dark")
# Themes: blue (default), dark-blue, green
customtkinter.set_default_color_theme("customTkinterTheme.json")
outputToScreen = customtkinter.CTkTextbox(window , width=400 , height=200)
outputToScreen.place(x=200, y=300)
def popupmsg(msg):
popup = customtkinter.CTk()
popup.title("!")
label = customtkinter.CTkLabel(popup, text=msg,)
label.pack(side="top", fill="x", pady=10)
B1 = customtkinter.CTkButton(popup, text="Okay", command=popup.destroy)
B1.pack()
popup.mainloop()
# create main window
# window specs are 700 x 350 and window is not able to be resizeable
# CREATING USER CONTROLS
# each button will print a list of items (number of items will be come from the entry userValue)
userEntry = customtkinter.CTkEntry(window)
# userValue = int(userValue)
userValue = ""
userEntry.place(x=325, y=200)
userEntry.insert(0, userValue)
userValueLabel = customtkinter.CTkLabel(
window, text="ENTER AMOUNT OF RECORDS YOU WOULD LIKE").place(x=275, y=170)
label = customtkinter.CTkLabel(window, text="INFOMATION GENERATOR by Noah Mackay "
).pack()
def outputEmails(userValue):
# function receives the amount of records the user wants to print
# function will be called when email button is clicked
# this function will clear the output file and then read open it
# will call the generateEmail function from scripts.py file
# outputs the amount of records based on the user input in the entry text box
userValue = int(userEntry.get())
outputFile = scripts.generateEmail(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING WORKED")
def outputNames(userValue):
# function receives the amount of records the user wants to print
# function will be called when email button is clicked
# this function will clear the output file and then read open it
# will call the generateEmail function from scripts.py file
# outputs the amount of records based on the user input in the entry text box
userValue = int(userEntry.get())
outputFile = scripts.generateName(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputCost(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generateCost(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputProduct(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generateProduct(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputPhoneNumber(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generatePhoneNumber(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.insert(0,outputFile)
popupmsg("PRINTING COMPLETED")
# creates 5 buttons each have their respective output function attached using command=
emailButton = customtkinter.CTkButton(window, text="EMAILS",
command=lambda: outputEmails(userValue)).place(x=5, y=40)
productButton = customtkinter.CTkButton(window, text="PRODUCTS",
command=lambda: outputProduct(userValue)).place(x=150, y=40)
phoneNumberButton = customtkinter.CTkButton(
window, text="PHONE NUMBERS" , command= lambda:outputPhoneNumber(userValue)).place(x=300, y=40)
costButton = customtkinter.CTkButton(window, text="PRICES",
command=lambda: outputCost(userValue)).place(x=450, y=40)
nameButton = customtkinter.CTkButton(
window, text="FIRST + LAST NAMES", command=lambda: outputNames(userValue)).place(x=600, y=40)
window.mainloop()
#file -> scripts.py
import random
def generateName(numberOfItemsNeed):
# opens 2 files. One containing first names and the other containing last names
firstNameFile = open('dataFiles\FirstNamesData.txt', 'r')
lastNameFile = open('dataFiles\LastNamesData.txt', 'r')
# builds values for the while statement and the return string
returnValue = ""
counter = 0
# builds the return string using a while loop and removing the newline character
# after each line from both files when being read
while counter < int(numberOfItemsNeed):
returnValue += str(firstNameFile.readline().strip("\n")
) + " " + str(lastNameFile.readline().strip("\n")) + "\n"
counter = counter + 1
# returns a list of "human" names in a single string divided by a newline character
return (returnValue)
def generateEmail(numberOfItemsNeed):
# opens a file containing a records of first names
firstNameFile = open('dataFiles\dictonary.txt', 'r')
counter = 0
# A list of commonly used email address suffixs
suffix = ['#gmail.com', '#gmail.ca', '#hotmail.com',
'#hotmail.ca', '#mail.com ', '#mail.ca', '#gov.ca']
returnValue = ""
while counter < int(numberOfItemsNeed):
returnValue += firstNameFile.readline().strip("\n") + \
str((random.randrange(0, 100))) + \
suffix[random.randrange(0, len(suffix))]+'\n'
counter = counter + 1
return (returnValue)
def generateCost(numberOfItemsNeed):
# generates a random item price in the inclusive range of 0.00$ to 1000.99$
counter = 0
cost = ""
while counter < int(numberOfItemsNeed):
cost += '$' + str(random.randrange(0, 1000)) + \
"." + str(random.randrange(0, 99)) + '\n'
counter = counter+1
return cost
def generateProduct(numberOfItemsNeed):
counter = 0
returnValue = ""
productList = open('dataFiles\itemData.txt', 'r')
while counter < int(numberOfItemsNeed):
returnValue += str(productList.readline()
).strip("\n") + str(generateCost(1))
counter = counter + 1
return (returnValue)
def generatePhoneNumber(numberOfItemsNeed):
counter = 0
returnValue = ""
while counter < int(numberOfItemsNeed):
firstNumber = str(random.randrange(100, 999))
secondNumber = str(random.randrange(1000, 9999))
thirdNumber = str(random.randrange(100, 999))
returnValue += firstNumber + "-" + secondNumber + "-" + thirdNumber + '\n'
counter = counter + 1
return (returnValue)
def shuffleFile(filePath):
lines = open(filePath).readlines()
random.shuffle(lines)
open(filePath, 'w').writelines(lines)
# shuffleFile('dataFiles\dictonary.txt')
Text widget indexes are strings of the form line.character with lines starting at 0 and characters starting at 1. So, to insert at the start you need to use the index "1.0", not 0. If you want to insert at the end you can use the special index "end". If the widget is empty, "1.0" and "end" yield identical results.
outputToScreen.insert("1.0", outputToFile)

Python Tkinter TextEditor how to save configuration changes

i'm very new to Tkinter but i tried to read all the documentation that i could and could not understand if i'm heading in the right direction or not.
Firstly, thank you for reading this.
In summary i'm trying to create a Text Editor with Tkinter. This text editor however must display the exact same file for every user which opens it in the same private network as it is to be used as a display Panel in order for everyone to be able to read anyone else's notices.
I Have still a lot to do but where i'm blocking right now and couldn't find an answer for is to be able to store the configurations changes that are applied to the text (Bold, color etc..)
the text itself is stored in a txt file that is automatically opened at the start of the program but i don't know a way to store the color and font style.
To apply the font and color to the text i use a counter that i apply to each tag change that is done (so the first area selection that will be changed will be named "colortag1" the second "colortag2" etc ..)
I don't know if it is possible to keep theses tags configurations and the count of my variable "counter" stored without reseting everything.
Would someone possibly have an idea?
I'm really sorry if it's not very understandable.
Here is my code:
import tkinter
import os
from tkinter import *
from tkinter.messagebox import *
from tkinter.filedialog import *
class Notepad:
#Creation of a Notepad Class
__root = Tk()
__countG = 1
__thisWidth = 300
__thisHeight = 300
__thisTextArea = Text(__root)
__thisMenuBar = Menu(__root)
__thisFileMenu = Menu(__thisMenuBar, tearoff=0)
__thisEditMenu = Menu(__thisMenuBar, tearoff=0)
__thisScrollBar = Scrollbar(__thisTextArea)
#The file that is always opened by the notepad
__file = "//srvad/echange/Python panel/paneltest.txt"
__thisTextArea.configure(font=("arial", "12" ,"normal"))
def __init__(self, **kwargs):
try:
self.__root.wm_iconbitmap("Notepad.ico")
except:
pass
try:
self.__thisWidth = kwargs['width']
except KeyError:
pass
try:
self.__thisHeight = kwargs['height']
except KeyError:
pass
#Creation of Edit Cascade
self.__thisMenuBar.add_cascade(label="Edit",
menu=self.__thisEditMenu)
#Name of the text editor
self.__root.title("Home Panel")
#Size and settings of the Notepad
screenWidth = self.__root.winfo_screenwidth()
screenHeight = self.__root.winfo_screenheight()
left = (screenWidth / 2) - (self.__thisWidth / 2)
top = (screenHeight / 2) - (self.__thisHeight / 2)
self.__root.geometry('%dx%d+%d+%d' % (self.__thisWidth,
self.__thisHeight,
left, top))
self.__root.grid_rowconfigure(0, weight=1)
self.__root.grid_columnconfigure(0, weight=1)
self.__thisTextArea.grid(sticky=N + E + S + W)
#Call of the Bold function
self.__thisEditMenu.add_command(label="Gras",font=("arial", "12", "bold"),
command=self.__gras)
self.__root.config(menu=self.__thisMenuBar)
self.__thisScrollBar.pack(side=RIGHT, fill=Y)
self.__thisScrollBar.config(command=self.__thisTextArea.yview)
self.__thisTextArea.config(yscrollcommand=self.__thisScrollBar.set)
file = open(self.__file, "r")
self.__thisTextArea.insert(1.0, file.read())
file.close()
#Bold function (the counter permit to generate a new tag name each time the function is called.
# The function check the counter number in order to decide if the text selection is in bold or normal font
# So the counter get +1 in one case an +2 in the other to differentiate them
def __gras(self):
sele=self.__thisTextArea.get(SEL_FIRST,SEL_LAST)
print (sele)
if self.__thisTextArea.tag_ranges('sel'):
if "colortag" + str(self.__countG -1) in self.__thisTextArea.tag_names(SEL_FIRST):
self.__thisTextArea.tag_add('colortag' + str(self.__countG), SEL_FIRST, SEL_LAST)
print ("le texte est gras")
self.__thisTextArea.tag_configure('colortag' + str(self.__countG),font=("arial", "12", "normal"))
self.__countG +=2
else:
self.__thisTextArea.tag_add('colortag' + str(self.__countG), SEL_FIRST, SEL_LAST)
print ('le texte est en normal')
self.__thisTextArea.tag_configure('colortag' + str(self.__countG), font=("arial", "12", "bold"))
self.__countG += 1
else:
pass
def __quitApplication(self):
self.__root.destroy()
#Save function that save the actual text in a .txt file
def __saveFile(self):
if self.__file == None:
self.__file = asksaveasfilename(initialfile='Untitled.txt',
defaultextension=".txt",
filetypes=[("All Files", "*.*"),
("Text Documents", "*.txt")])
if self.__file == "":
self.__file = None
else:
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
self.__root.title(os.path.basename(self.__file) + " - Notepad")
else:
file = open(self.__file, "w")
file.write(self.__thisTextArea.get(1.0, END))
file.close()
def run(self):
self.__root.mainloop()
notepad = Notepad(width=600, height=400)
notepad.run()
'''
I recommend that you look into Pythons pickle functionality, there is no way to do what you want without saving the tags in a separate file or writing the tags into the file itself.

Pass correct result out of authentication loop

I am creating a login system which retrieves the details within an entry box and compares it to details on a database. If the details entered are found on the database, the Bottom() function is ran. If details are not found, the user is requested to try again.
Currently, the program loops until it is found. However, because I have set up an else statement, if the first item in the database is not the details entered, the else section will still run. Is there a way I can change this so that else is else and last value in the database?
Here is the function:
#Retrieves the information entered into entry box
def Get_Details():
user_namev2=user_name.get().lower() #Make it so entry box goes red if passwords password is incorrect, and red if username is incorrect/not fault
user_passwordv2=user_password.get().lower()
with open ('Accounts.csv', 'r') as Account_file:
reader = csv.reader(Account_file)
for row in reader:
for field in row:
if row[0] == user_namev2 and row[1] == user_passwordv2:
Bottom()
break
else:
nomatch_label = Label(canvas, width = 40, height = 2, text = "USERNAME AND PASSWORD NOT FOUND", fg = "red", bg = "gray21", font = font2)
canvas_nomatch_label = canvas.create_window(500, 550, window = nomatch_label)
name_entry.config(fg = "red")
password_entry.config(fg="red")
break
This should hopefully work the way you intended, now it loops over the rows and checks username/password against row[0] and row[1]. If it finds a match it breaks and will not execute the else connected to the for-loop.
Also I removed the for-loop over row as the field variable wasn't used anyhow.
#Retrieves the information entered into entry box
def Get_Details():
user_namev2=user_name.get().lower() #Make it so entry box goes red if passwords password is incorrect, and red if username is incorrect/not fault
user_passwordv2=user_password.get().lower()
with open ('Accounts.csv', 'r') as Account_file:
reader = csv.reader(Account_file)
for row in reader:
if row[0] == user_namev2 and row[1] == user_passwordv2:
Bottom()
break
else:
nomatch_label = Label(canvas, width = 40, height = 2, text = "USERNAME AND PASSWORD NOT FOUND", fg = "red", bg = "gray21", font = font2)
canvas_nomatch_label = canvas.create_window(500, 550, window = nomatch_label)
name_entry.config(fg = "red")
password_entry.config(fg="red")
#Retrieves the information entered into entry box
def Get_Details():
user_namev2=user_name.get().lower() #Make it so entry box goes red if passwords password is incorrect, and red if username is incorrect/not fault
user_passwordv2=user_password.get().lower()
with open ('Accounts.csv', 'r') as Account_file:
reader = csv.reader(Account_file)
found = False
for row in reader:
for field in row:
if row[0] == user_namev2 and row[1] == user_passwordv2:
Bottom()
found = True
break
else:
if not found:
nomatch_label = Label(canvas, width = 40, height = 2, text = "USERNAME AND PASSWORD NOT FOUND", fg = "red", bg = "gray21", font = font2)
canvas_nomatch_label = canvas.create_window(500, 550, window = nomatch_label)
name_entry.config(fg = "red")
password_entry.config(fg="red")
break
note that the else has been shifted back to pair with the for loop

How to change an empty label to a multi-line label in python tkinter

I have a label that I want to be empty until a button is pressed that searches a csv file to find scores from entries of the same name as an entered name. Any values that are found to be displayed into a label, currently only the first values are shown by the list, thanks.
entSearch = Entry(window)
lblSearch = tkinter.Label(window, text="Search for your previous scores!")
btnSearch = Button(window, text="Search!",command=search)
lblSearched = tkinter.Label(window, text="")
def search():
file1=open("scores.csv","r")
csvreader=csv.reader(file1)
for x in csvreader:
if entSearch.get() == x[0]:
results = x[0]+" "+x[1]+"\n"
lblSearched.config(text=results)
You can connect all in one text and later put it in Label
searched_text = entSearch.get()
full_text = ''
for row in csvreader:
if row[0] == searched_text:
# with '\n'
full_text += "{} {}\n".format(row[0], row[1])
lblSearched.config(text=full_text)
or with join() (it will not add \n after last line)
searched_text = entSearch.get()
all_lines = []
for row in csvreader:
if row[0] == searched_text:
# WITHOUT '\n'
all_lines.append("{} {}".format(row[0], row[1]))
full_text = '\n'.join(all_lines)
lblSearched.config(text=full_text)
In your current code you can use
lblSearched['text'] += results
or
lblSearched.config(text=lblSearched.cget('text') + results)
but it is less readable.

str.find() = TypeError: unsupported operand type(s) for +: 'int' and 'str' ..?

from tkinter import *
master = Tk()
master.title("Caeser Cipher Program")
master.geometry("300x200")
frame1 = Frame(master)
frame2 = Frame(master)
frame3 = Frame(master)
frame4 = Frame(master)
frame5 = Frame(master)
frame6 = Frame(master)
global encryptedText
global file
global shiftKey
file = ""
encryptedText = ""
removeSpaces = ""
def Start():
frame1.grid()
Question = Label(frame1, text = "Would you like to encrypt or decrypt a statement?\n\n\n")
Question.grid(row = 0, column = 1)
ButtonPlace1 = Button(frame1, text = "Encrypt", command = EncryptChosen)
ButtonPlace2 = Button(frame1, text = "Decrypt", command = decrypt_command)
ButtonPlace1.place(x = 75, y = 50, anchor = "c")
ButtonPlace2.place(x = 175, y = 50, anchor = "c")
def EncryptChosen():
frame1.destroy()
frame2.grid()
Question = Label(frame2, text = "What would you like to shift it by?\t\t\t\n\n\n\n\n ")
ButtonPlace3 = Entry(frame2)
def SubmitEncryptionKey():
shiftKey = ButtonPlace3.get()
frame2.destroy()
frame3.grid()
Question = Label(frame3, text = "What would you like it to say?\t\t\t\n\n\n\n\n" )
ButtonPlace5 = Entry(frame3)
def SubmitText():
file = ButtonPlace5.get()
frame3.destroy()
frame4.grid()
Question = Label(frame4, text = "Would you like to remove spaces?\t\t\t\n\n\n\n\n")
Question.grid(row = 0, column = 1)
def doRemoveSpaces():
global spacesStatement
global removeSpaces
spacesStatement = "spaces will be removed"
removeSpaces = "True"
ReadyToEncrypt()
ButtonPlace7 = Button(frame4, text = "Yes", command = doRemoveSpaces)
def doNotRemoveSpaces():
global spacesStatement
global removeSpaces
spacesStatement = "spaces will not be removed"
removeSpaces = "False"
ReadyToEncrypt()
ButtonPlace8 = Button(frame4, text = "No", command = doNotRemoveSpaces)
def ReadyToEncrypt():
frame4.destroy()
frame5.grid()
Question = Label(frame5, text = file + "\n will be encrypted by " + shiftKey + " and \n" + spacesStatement + ".\t\t\t\n\n\n\n")
Question.grid(row = 0, column = 1)
def encryptSetup():
def encrypt(character):
alphabet = 'abcdefghijklmnopqrstuvwxyz '
character = character.lower()
if character.isalpha():
position = str(alphabet).find(character) + shiftKey
if position > 25:
position -= 26
return alphabet[position]
else:
return character
for line in file:
for c in line:
global encryptedText
encryptedText = encryptedText + encrypt(c)
if removeSpaces == "True":
encryptedText = encryptedText.replace(" ","")
frame5.destroy()
frame6.grid()
Question = Label(frame6, text = "Here is your encrypted message: \n" + encryptedText)
Question.grid(row = 0, column = 1)
ButtonPlace9 = Button(frame5, text = "Encrypt!", command = encryptSetup)
ButtonPlace9.place(x=175,y=50)
ButtonPlace7.place(x = 75, y = 50, anchor = "c")
ButtonPlace8.place(x = 175, y = 50, anchor = "c")
ButtonPlace6 = Button(frame3, text = "Submit", command = SubmitText)
Question.grid(row = 0, column = 1)
ButtonPlace5.place(x=50,y=50)
ButtonPlace6.place(x=175,y=45)
ButtonPlace4 = Button(frame2, text = "Submit", command = SubmitEncryptionKey)
Question.grid(row = 0, column = 1)
ButtonPlace3.place(x=50,y=50)
ButtonPlace4.place(x=175,y=45)
frame1.grid()
Question = Label(frame1, text = "Would you like to encrypt or decrypt a statement?\n\n\n")
Question.grid(row = 0, column = 1)
ButtonPlace1 = Button(frame1, text = "Encrypt", command = EncryptChosen)
ButtonPlace2 = Button(frame1, text = "Decrypt", command = "")
ButtonPlace1.place(x = 75, y = 50, anchor = "c")
ButtonPlace2.place(x = 175, y = 50, anchor = "c")
master.loop()
This is my code for a program that allows you to encrypt or decrypt a statement in the form of a caeser cypher. So far, I have coded it so that you go through it, choose what you want it to be shifted by, what you want encrypted, and whether or not you want spaces to be removed. I haven't started working on the decryption yet. However, in the code that, after all necessary variables have been collected, actually encrypts the statement I encountered a problem. I created a string called 'alphabet' that stores the entire alphabet. When the function is run through, I need to find where the character is in the alphabet so I can shift it. However, when I had done this and ran it I got an error:
position = alphabet.find(character) + shiftKey
TypeError: unsupported operand type(s) for +: 'int' and 'str'
Also, when I use the for loop to run through the entire statement and encrypt it all, I encounter this error:
UnboundLocalError: local variable 'encryptedText' referenced before assignment
This is a problem as essentially what I need to do is add each encrypted character to the encrypted text string but this is preventing me doing it. Please can somebody help in any way as I need to finish this project for Monday 9th March 2017.
alphabet.find(chr) returns an integer, shiftkey is a string -- change one or the other to match.
encrypted_text is a local variable in its function -- the global encrypted_text declaration you have at the top in the global scope is useless. global is meant to be used inside functions to tell Python that the variable name listed is not local to the function, and to go find it in the global scope.

Categories