Below is the code I have so far for a simple Caesar cipher program, I am having issues trying to output the encoded data to the graphics window.
The program runs right. But the only output that appears on the screen is the first letter of the coded message, I need the whole coded message to appear on the graphics window.
I think it might be a problem with my loop but can't figure it out. I tried moving the loop around but that just gave two or three repetitions of the first letter.
Any help would be appreciated.
from graphics import*
def main():
win = GraphWin("Caeser Cipher",500,500)
win.setCoords(0.0,0.0,5.0,5.0)
Text(Point(2,4.8),"Caesar Ciper").draw(win)
label1 = Text(Point(1,4),"Please input file:").draw(win)
inputFileName = Entry(Point(2.5,4,),20)
inputFileName.draw(win)
button1 = Text(Point(2.5,3.5),"Open").draw(win)
Rectangle(Point(2.25,3.3),Point(2.75,3.7)).draw(win)
label = Text(Point(1,2.5),"Please input step:")
label.draw(win)
inputstep = Entry(Point(2.5,2.5),20)
inputstep.draw(win)
button2 = Text(Point(2.5,2.0),"Encode").draw(win)
Rectangle(Point(2.25,1.8),Point(2.75,2.2)).draw(win)
button3 = Text(Point(4,1),"Save").draw(win)
Rectangle(Point(3.75,0.8),Point(4.25,1.2)).draw(win)
button4 = Text(Point(4,0.5),"Quit").draw(win)
Rectangle(Point(3.75,0.3),Point(4.25,0.7)).draw(win)
output2 = Text(Point(2.5,1.5),' ')
output2.setTextColor('blue')
output2.draw(win)
while True:
P = win.getMouse()
if(P.getX()>2.25 and P.getX()<2.75 and P.getY()>3.3 and P.getY()<3.7):
fnamein = inputFileName.getText()
infile = open(fnamein, encoding='utf-16', mode='r')
content = infile.read()
output = Text(Point(2.5,3),100)
output.setText(content)
output.setTextColor('red')
output.draw(win)
#infile.close()
if(P.getX()>2.25 and P.getX()<2.7 and P.getY()>1.8 and P.getY()<2.2):
content.strip()
words = content.split()
inputstep1 = inputstep.getText()
#print(inputstep1)
encodedcontent = ' '
for numStr in content:
codeNum = ord(numStr)
#print(codeNum)
encodedcontent = chr(codeNum-eval(inputstep1))
encodedcontent_ascii = ord(numStr)-int(inputstep1)
#print(encodedcontent)
#encodedcontent = encodedcontent + ''
print(encodedcontent)
if(encodedcontent_ascii)<ord('a'):
encodedcontent_ascii = encodedcontent_ascii + 26
#print(encodedcontent_ascii)
'''if str.isalpha(encodedcontent):
encodedcontent = encodedcontent + chr(encodedcontent_ascii)
else:
label.setTextColor('red')'''
encodedcontent = encodedcontent + chr(encodedcontent_ascii)
output2.setText(encodedcontent)
if(P.getX()>3.75 and P.getX()<4.25 and P.getY()>0.8 and P.getY()<1.2):
fnameout = 'encrypt.txt'
data = encodedcontent
outfile = open(fnameout,encoding='utf-16',mode='w')
outfile.write(data)
outfile.close()
if(P.getX()>3.75 and P.getX()<4.25 and P.getY()>0.3 and P.getY()<0.7):
win.close()
main()
I think the problem lies in this loop:
encodedcontent = ' ' # initialise
for numStr in content:
...
encodedcontent = chr(codeNum-eval(inputstep1)) # overwrite
...
encodedcontent = encodedcontent + chr(encodedcontent_ascii) # add
encodedcontent will only be two characters at most, when presumably you want to build up the whole string.
More generally, putting all of your code into one place makes this difficult to debug. I suggest breaking it into smaller functions; at the very least, separate the encryption of a string out from the user interface.
Related
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)
I have 4 functions that should grab some text from a specific docx file that are highlighted scan4<colour> is the varialbe of the text, these functions are near identical but are searching and replacing different highglighted text, they print out the same but they dont replace the text
these are 2 functions of 4, the yellow one works while the green one doesnt
what the code does is it searches and replaces the text then encrypts then uses the encrypted string into the main document, the other does the exact same but searches for a different highlighted colour. I try to encrypt the first function works but the second one doesn't
This code searches for yellow encodes the text and then replaces it so the un-encrypted document shows the encrypted string of the contents
def securi1_key():
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
global key1
key1 = file.read()
file.close()
def rewrite_yellow():
securi1_key()
save_yellow_text()
# get key from file
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi1.key", "rb")
texty = scan4yellow.decode("utf-8")
encodedy = texty.encode()
# encrypt message
f = Fernet(key1)
encryptedy = f.encrypt(encodedy)
print(scan4yellow)
print(scan4yellow.decode("utf-8"))
document = docx.Document(f1)
for paragraph in document.paragraphs:
if scan4yellow.decode("utf-8") in paragraph.text:
inline = paragraph.runs
# loops for runs
for i in range(len(inline)):
if scan4yellow.decode("utf-8") in inline[i].text:
text = inline[i].text.replace(scan4yellow.decode("utf-8"), encryptedy.decode("utf-8"))
inline[i].text = text
document.save(f1)
def save_yellow_text():
securi1_key()
fp = f1
p = Path(fp)
filename1 = p.stem
storedtexty = filename1 + " Yellow Text"
storedtextencryptedy = storedtexty + ".encrypted"
list_of_files = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")
if storedtexty in list_of_files:
storedtexty = (storedtexty + "1")
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtexty, "w+")
file.write(scan4yellow.decode("utf-8"))
input_file1 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtexty)
if storedtextencryptedy in list_of_files:
storedtextencryptedy = (storedtextencryptedy + "1")
output_file1 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextencryptedy)
with open(input_file1, "rb") as f:
data = f.read()
fernet = Fernet(key1)
encrypted = fernet.encrypt(data)
with open(output_file1, "wb") as f:
f.write(encrypted)
file.close()
os.remove(input_file1)
this code should do the exact same but for the colour green :
def securi2_key():
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi2.key", "rb")
global key2
key2 = file.read()
file.close()
def rewrite_green():
securi2_key()
save_green_text()
# get key from file
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Keys/Securi2.key", "rb")
textg = scan4green.decode("utf-8")
encodedg = textg.encode()
print(encodedg)
# encrypt message
f = Fernet(key2)
encryptedg = f.encrypt(encodedg)
print(encryptedg)
document = docx.Document(f1)
for paragraph in document.paragraphs:
if scan4green.decode("utf-8") in paragraph.text:
inline = paragraph.runs
# loops for runs
for i in range(len(inline)):
if scan4green.decode("utf-8") in inline[i].text:
text = inline[i].text.replace(scan4green.decode("utf-8"), encryptedg.decode("utf-8"))
inline[i].text = text
document.save(f1)
def save_green_text():
securi2_key()
fp = f1
p = Path(fp)
filename2 = p.stem
storedtextg = filename2 + " Green Text"
storedtextencryptedg = storedtextg + ".encrypted"
list_of_files = os.listdir("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/")
if storedtextg in list_of_files:
storedtextg = (storedtextg + "1")
file = open("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextg, "w+")
file.write(scan4green.decode("utf-8"))
print(scan4green.decode("utf-8") + "tested1")
input_file2 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextg)
if storedtextencryptedg in list_of_files:
storedtextencryptedg = (storedtextencryptedg + "1")
output_file2 = ("C:/Users/devff/PycharmProjects/SecurityLevels/Stored Text/" + storedtextencryptedg)
with open(input_file2, "rb") as f:
data = f.read()
fernet = Fernet(key2)
encrypted = fernet.encrypt(data)
with open(output_file2, "wb") as f:
f.write(encrypted)
file.close()
os.remove(input_file2)
I should have some incoherent string replace the actual text and the actual text saved in another file encrypted, but all this does is work for the first yellow function but not the green function
Ideally it should take the text from the read in file, make a copy write it out to a file and encrypt that then take the string of encryption from that and replace it where it was in the read in file, but it only works for the yellow code while the green and the other code which are near identical do not work
I have found an answer, what I changed has nothing to do with the code I provided but when I read in the text it was scan4green = (word.find(tag_t).text.encode('utf-8').lower()). this apparently caused it not to work properly but the scan4yellow did work because i didn't have .lower() attached to the end.
So I'm currently trying to write some code that opens and reads a text file. The text file contains a short paragraph. Within the paragraph, there are some words with brackets around them, which could look like: "the boy [past_tense_verb] into the wall." I am trying to write code that looks for the brackets in the text file, and then displays to the user the words in the text file, for the user to then write some input that will replace the bracketed words. This is the code I have so far:
f = open('madlib.txt', 'r')
for line in f:
start = line.find('[')+1
end = line.find(']')+1
word = line[start:end+1]
inputword = input('Enter a ' + word + ': ')
print(line[:start] + inputword + line[end:])
Any help is greatly appreciated - thanks!
import re
with open('madlib.txt', 'r') as f:
data = f.read()
words_to_replace = re.findall(r"\[(\w+)\]", data)
replace_with = []
for idx, i in enumerate(words_to_replace):
print(f"Type here replace \033[1;31m{i}\033[1;m with:", end =" ")
a = input()
replace_with.append(a)
for idx, i in enumerate(replace_with):
data = data.replace(words_to_replace[idx], i)
with open('newmadlib.txt', 'w') as f:
f.write(data)
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hey guys so I have a lengthy code here I need help with,
specifically: my end process is an assignment creating a word cloud, But I haven't even start at that point yet. As of now, I've been able to create the function of creating a frequency accumulator and my first GUI platform.
When running the program, the gui asks the user to type in the file name of their program. However, you can type gibberish or even leave it blank, click the transform file button, and it still opens up Shell and prompts the user for the text file name and then the number of words they want in the list.
I don't even want the 2nd part (asking how many words) but I didn't know another way of doing it for my frequency counter.
from graphics import *
##Deals with Frequency Accumulator##
def byFreq(pair):
return pair[1]
##Function to allow user to upload their own text document##
def FileOpen(userPhrase):
filename = input("Enter File Name (followed by .txt): ")
text = open(filename, 'r').read()
text = text.lower()
for ch in ('!"#$%&()*+,-./:;<=>?#[\\]^_{}~'):
text = text.replace(ch, " ")
words = text.split()
counts = {}
for w in words:
counts[w] = counts.get(w,0) + 1
n = eval(input("Output how many words?"))
items = list(counts.items())
items.sort(key=byFreq, reverse=True)
for i in range(n):
word, count = items[i]
print("{0:<15}{1:>5}".format(word, count))
##This Function allows user to simply press button to see an example##
def Example():
win = GraphWin("Word Cloud", 600, 600)
file = open("econometrics.txt", "r", encoding = "utf-8")
text = file.read()
text = text.lower()
for ch in ('!"#$%&()*+,-./:;<=>?#[\\]^_{}~'):
text = text.replace(ch, " ")
words = text.split()
counts = {}
for w in words:
counts[w] = counts.get(w,0) + 1
n = eval(input("Output how many words?"))
items = list(counts.items())
items.sort(key=byFreq, reverse=True)
for i in range(n):
word, count = items[i]
print("{0:<15}{1:>5}".format(word, count))
#########################################################################
##Gold Boxes##
def boxes(gwin, pt1, pt2, words):
button = Rectangle(pt1, pt2)
button.setFill("gold")
button.draw(gwin)
#Middle of the box coordinates
labelx = (pt1.getX() + pt2.getX())/2.0
labely = (pt1.getY() + pt2.getY())/2.0
#Labels
label = Text(Point(labelx,labely),words)
label.setFill("black")
label.draw(gwin)
####GUI function#####
def main():
#Creates the actual GUI
win = GraphWin("Word Cloud Prompt", 600, 600)
#Box which user types into:
inputBox = Entry(Point(300,150),50)
inputBox.draw(win)
#Gold Boxes at Top
boxes(win, Point(220,300), Point(370,350), "Transform Text File")
boxes(win, Point(220,400), Point(370,450), "Example text file")
#Tells user what to do
prompt = Text(Point(300,25),"Welcome to the Word Cloud program!")
prompt.draw(win)
prompt = Text(Point(300,125),"Enter your textfile name")
prompt.draw(win)
prompt = Text(Point(300,180),"Want to see our own file into a Word Cloud? Click below")
prompt.draw(win)
#display answer
display = Text(Point(300, 500),"")
display.draw(win)
#User Clicks a box:
pt = win.getMouse()
#Store user info
userPhrase = inputBox.getText()
key = inputBox.getText()
#Incase a button isn't clicked
output = "No button was clicked, Please restart program"
#Clicking the Transform Text File Button
if pt.getY() >= 300 and pt.getY() <= 350:
if pt.getX() >= 220 and pt.getX() <= 370:
output = FileOpen(userPhrase)
#Clicking the Example Text File Button
if pt.getY() >= 400 and pt.getY() <= 450:
if pt.getX() >= 220 and pt.getX() <= 370:
output = Example()
#State Answer
display.setText(output)
display.setFill("purple3")
display.setStyle("bold")
prompt.setText("Thank You! Click anywhere to close!")
prompt.setFill("red")
#closing program
pt = win.getMouse()
win.close()
main()
(Editor's Note: I've modified some of the formatting for my ease of reading, but the function will be identical)
def FileOpen(userPhrase):
"""FileOpen allows users to upload their own text document."""
filename = input("Enter File Name (followed by .txt): ")
text = open(filename, 'r').read()
text = text.lower()
for ch in ('!"#$%&()*+,-./:;<=>?#[\\]^_{}~'):
text = text.replace(ch, " ")
words = text.split()
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
n = eval(input("Output how many words?"))
items = list(counts.items())
items.sort(key=byFreq, reverse=True)
for i in range(n):
word, count = items[i]
print("{0:<15}{1:>5}".format(word, count))
This is the function we're concerned with. You call it with an argument userPhrase that comes from a gui text entry field, but then you never use userPhrase anywhere in the function. Consider instead:
def file_open(userPhrase=None):
# file_open is lowercase and snake_case for PEP8
# userPhrase=None to make it an optional argument
filename = userPhrase if userPhrase is not None else \
input("Enter file name (including extension): ")
...
Then you'll have to call it differently if you want file_open to prompt for a filename if not given one.
def main():
...
if 300 <= pt.getY() <= 350 and 220 <= pt.getX() <= 370:
# you can chain conditionals as above. It makes it much easier to read!
# `a <= N <= b` is easily read as `N is between a and b`
userPhrase = inputBox.getText()
if userPhrase.strip(): # if there's something there
file_open(userPhrase)
else:
file_open()
I have a python code that a friend made , as I have very small knowledge of python..
I want to convert it into a GUI as we will distribute the code as a program for it to be beginner-friendly .
anyways here's the code:
import time, os, sys
try:
if len(sys.argv) < 2:
fn = raw_input("Enter the name of the file you want to edit: ")
else: fn = sys.argv[1]
f = open(fn)
b = f.read()
for i in b[:300]:
print hex(ord(i))[2:],
f.close()
line = str(0x15c)+'-'+str(0x15f)
if len(sys.argv)<3:
hexcode = raw_input("3 bytes color hex number: ")
else: hexcode = sys.argv[2]
if not hexcode.startswith('0x'):
hexcode = '0x'+hexcode
hexstr = '0x'
start = int(line.split('-')[0])
end = int(line.split('-')[1])
for i in b[start:end]:
hexstr+=hex(ord(i))[2:]
ascii = ''
for i in range(2,len(hexcode),2):
char = chr(int(hexcode[i:i+2],16))
ascii+=char
b = b[:start]+ascii+b[end:]
for i in b[:300]:
print hex(ord(i))[2:],
except Exception, x:
print x
time.sleep(3)
finally:
f = open(fn,'wb')
f.write(b)
f.close()
Now I found this on a tutorial but don't know how to use it:
#simple GU0I
from Tkinter import *
root = Tk()
root.title("BreffHexReplace")
root.geometry("400x200")
app = Frame(root)
app.grid()
label = Label(app, text = "This is a label!")
label.grid()
root.mainloop()
Any help?
thanks!
also one more thing , in this code , after I type in the name or the replacor hex , it shows me a list of hex , how can I make it not shown?
thanks!
Because this program is so simple, you can try EasyGui( easygui.sourceforge.net/ ). To start, add import easygui as eg. This line loads the EasyGui module. Next, replace fn = raw_input("Enter the name of the file you want to edit: ") with fn = eg.fileopenbox(title = 'HexReplace', msg = 'Browse to the file you wish to edit'). This opens a box to browse to the wanted file. Also replace hexcode = raw_input("3 bytes color hex number: ") with hexcode = eg.enterbox(msg = '3 bytes color hex number', title = 'HexReplace'). This pops up an input box. Replace print x with eg.msgbox(title = 'HexReplace', msg = x). This shows a message box with the exception. The title argument is the window title. To remove the hex list, add between the imports and the try block: null = open(os.devnull, 'W's); oldstdout = system.stdout; sys.stdout = null
This will silence all print messages.