How do I print the variable "new_text" in line in python - python

text_box is a tkinter text box
I am trying to convert source_text's letters to the number corresponding to the position of said letter
such that a or A = 1, b or B = 2 and print it the console
def enter():
#don't use 1 in place of 1.0
source_text=text_box.get(1.0, END)
def alphabet_position(text):
dict = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
new_text = text.lower(source_text)
for i in new_text:
if i in dict:
new_text = new_text.replace(i, dict[i])
print (new_text)
enter is called as such
btn = Button(root, text = "Enter", command = enter)

dict = {'a':'1','b':'2','c':'3','d':'4','e':'5','f':'6','g':'7','h':'8','i':'9','j':'10','k':'11','l':'12','m':'13','n':'14','o':'15','p':'16','q':'17','r':'18','s':'19','t':'20','u':'21','v':'22','w':'23','x':'24','y':'25','z':'26'}
new_text = text.lower()
for i in new_text:
if i in dict:
return new_text.replace(i, dict[i])
def enter():
print (alphabet_position(text_box.get(1.0, END)))

Related

How to highlight whole syntax(including every modules's Keywords,class,etc.) of python in text widget in python tkinter

I am creating code editor, I want to highlight every code properly. I have created a code to highlight code
and I have created a different function to highlight string and comments
but when I type any code from which already contain some color to highlight doesn't show string color inside "" but I want only that code show it's own color outside "" not inside
for example if I type from inside it "" than want that code show lime color which is color of string set my me but it show cyan(set by me for outside "")
this is my code
from tkinter import*
def Keys_word(Keys_list):
for i in Keys_list:
editor.tag_remove(i,"1.0",END)
pos = 1.0
while True:
pattern = r"\m{}\M".format(i)
pos = editor.search(pattern,pos,regexp=True,stopindex=END)
if not pos:
break
last_pos = "%s+%sc"%(pos,len(i))
editor.tag_add(i,pos,last_pos)
pos = last_pos
editor.tag_configure(i,foreground=Keys_list[i])
root.after(1000,lambda:Keys_word(Keys_list))
Custom_highlight_for_string()
return
def Custom_highlight_for_string():
myCount = IntVar()
regex_pattern = [r'".*"',r'#.*',r"'''.*'''",r"'.*'"]
for pattern in regex_pattern:
editor.mark_set("start","1.0")
editor.mark_set("end",END)
num = int(regex_pattern.index(pattern))
while True:
index = editor.search(pattern,"start","end",count=myCount,regexp=True)
if index == "": break
if num == 0:
editor.tag_add(color[0],index,"%s+%sc"%(index,myCount.get()) )
elif num == 1:
editor.tag_add(color[1],index,index +" lineend")
elif num == 2:
editor.tag_add(color[0],index,"%s+%sc"%(index,myCount.get()) )
elif num == 3:
editor.tag_add(color[0],index,"%s+%sc"%(index,myCount.get()) )
editor.mark_set("start","%s+%sc"%(index,myCount.get()))
root = Tk()
Keys_list = {"def":"blue","from":"cyan","import":"cyan","class":'orange'}
color = ["lime","red"]
editor = Text(font="Consolas 11")
editor.tag_configure("lime",foreground="lime")
editor.tag_configure("red",foreground="red")
editor.pack()
root.after(1000,lambda:Keys_word(Keys_list))
root.mainloop()
This is what I have created
I have found this solution
this solution solve my problem
from tkinter import*
def Keys_word(Keys_list):
for i in Keys_list:
editor.tag_remove(i,"1.0",END)
pos = 1.0
while True:
pattern = r"\m{}\M".format(i)
pos = editor.search(pattern,pos,regexp=True,stopindex=END)
if not pos:
break
last_pos = "%s+%sc"%(pos,len(i))
editor.tag_add(i,pos,last_pos)
pos = last_pos
# editor.tag_configure(i,foreground=Keys_list[i])
root.after(1000,lambda:Keys_word(Keys_list))
Custom_highlight_for_string()
return
def Custom_highlight_for_string():
myCount = IntVar()
regex_pattern = [r'".*"',r'#.*',r"'''.*'''",r"'.*'"]
for pattern in regex_pattern:
editor.mark_set("start","1.0")
editor.mark_set("end",END)
num = int(regex_pattern.index(pattern))
while True:
index = editor.search(pattern,"start","end",count=myCount,regexp=True)
if index == "": break
if num == 0:
editor.tag_add(color[0],index,"%s+%sc"%(index,myCount.get()) )
elif num == 1:
editor.tag_add(color[1],index,index +" lineend")
elif num == 2:
editor.tag_add(color[0],index,"%s+%sc"%(index,myCount.get()) )
elif num == 3:
editor.tag_add(color[0],index,"%s+%sc"%(index,myCount.get()) )
editor.mark_set("start","%s+%sc"%(index,myCount.get()))
root = Tk()
Keys_list = {"def":"blue","from":"cyan","import":"cyan","class":'orange'}
color = ["lime","red"]
editor = Text(font="Consolas 11")
for i in Keys_list:
editor.tag_configure(i,foreground=Keys_list[i])
editor.tag_configure("lime",foreground="lime")
editor.tag_configure("red",foreground="red")
editor.pack()
root.after(1000,lambda:Keys_word(Keys_list))
root.mainloop()

How to clear a bunch of python labels but only when they are called

Hello fellow stackoverflowers,
I'm writing a small program that does some database stuff and I am trying to delete a label but only when it is called.
Here is one of my full functions but the part at the bottom is where I am trying to delete the labels.
def entry_a_result(self):
count = 0
counta = 0
fullfile = fullGUI.f_or()
if len(self.e.get()) > 0:
#print(self.e.get())
file_obj = open(fullfile, "r+")
fullstring = self.e.get()
x = fullstring[5:9]
try:
while(fullstring.startswith("get *") and count < 1):
self.la = Label(root, text = file_obj.read() + "\n" + "--------")
self.la.pack(side=TOP, anchor=N)
count = 1
while(fullstring.startswith("get |" + x) and count < 1):
count = 1
lines = file_obj.readlines()
for line in lines:
if x in line:
self.lb = Label(root, text=line + "\n" + "--------")
self.lb.pack(side=TOP, anchor=N)
else:
pass
**while(fullstring.startswith("clear") and count < 1):
count = 1
labela = self.la.winfo_exists()
labelb = self.lb.winfo_exists()
if labela == 1:
self.la.destroy()
if labelb == 1:
self.lb.destroy()**
What seems to be happening is that winfo_exists() is only working when the label is created and won't attach itself to the variable otherwise.
To clear up any confusion,
I'm trying to destroy or remove a label when and only when the label is existing in this case whenever I call a certain parameter within the program, which is currently working(in that my params work)

Python tkinter get() has no attribute

I'd like to use each variable in the list in an Entry widget, and get the text after pressing a button.
self.input_text = ['l1', 'l2', 'l3']
self.activeRow = 3
for e in self.input_text:
e = StringVar()
t = Entry(textvariable=e)
t.grid(row=self.activeRow,column=4,columnspan=2,sticky=W)
self.activeRow += 1
Eventually, I'd like to write the value of each variable in the list to a file but for now, I can't seem to print self.input_text[0] after the button press.
button1 = Button(text='Write',command=self.__writeNewInfo, width = 15)
button1.grid(row=self.activeRow,column=5,sticky=W)
def __writeNewInfo(self):
x = self.input_text[0].get()
y = self.input_text[1].get()
z = self.input_text[2].get()
print x
print y
print z
You are doing the wrong thing when creating the instances of StringVar. You set e to be the item in the list, then overwrite it as an empty StringVar. Instead try:
for i, e in enumerate(self.input_text):
self.input_text[i] = StringVar() #Overwrite this item in the list
self.input_text[i].set(e) #Set the StringVar to take the value from the list
t = Entry(textvariable=self.input_text[i])
t.grid(row=self.activeRow,column=4,columnspan=2,sticky=W)
self.activeRow += 1
self.input_text is basically a list of strings. If you want to retrieve something from an entry you need to keep the variable of this entry and call get() on it.
for example:
self.input_text = ['l1', 'l2', 'l3']
self.entries = []
self.activeRow = 3
for e in self.input_text:
e = StringVar()
t = Entry(textvariable=e)
t.grid(row=self.activeRow,column=4,columnspan=2,sticky=W)
self.activeRow += 1
self.entries.append(t)
button1 = Button(text='Write',command=self.__writeNewInfo, width = 15)
button1.grid(row=self.activeRow,column=5,sticky=W)
def __writeNewInfo(self):
x = self.entries[0].get()
y = self.entries[1].get()
z = self.entries[2].get()
print x
print y
print z

Python hangman problems

So I have my hangman almost working however, it is only placing the first correct guess on the first line, and not continuing if I guess the second letter correctly. Also, no matter what letter I guess, it always draws the head on the third letter guessed. I have it narrowed down to my getGuessLocationInPuzzle function, where my index is always printing out zero even if I have guessed my second letter. I've been staring at this code for 2 and 1/2 hours, and can't solve it. Please help!
''' Import Statements '''
from graphics import *
import copy
import random
import string
def drawGallows(window):
gallows = Rectangle(Point(300,280),Point(200,300))
gallows.draw(window)
gallows = Line(Point(250,300),Point(250,100))
gallows.draw(window)
gallows = Line(Point(250,100),Point(120,100))
gallows.draw(window)
gallows = Line(Point(120,100),Point(120,120))
gallows.draw(window)
def getPuzzle():
fh = open("puzzle.txt","r")
fileList = fh.read()
files = string.split(fileList)
puzzle = random.choice(files)
return puzzle
def drawPuzzle(length, window):
lines = Line(Point(15,275),Point(25,275))
for index in range(length):
newline = copy.copy(lines)
newline.move(20,0)
newline.draw(window)
def getGuess(entry, window):
letter = entry.getText()
return letter
def getValidGuess(Validguesses, entry, window):
guess = getGuess(entry, window)
for index in Validguesses:
if guess == index:
return guess
def createTextOverlay(guess):
textstring = ""
num = ord(guess)
for index in range(num - ord("a")):
textstring = textstring + " "
textstring= textstring + guess
for index in range(25-(ord(guess)-ord("a"))):
textstring = textstring+" "
overlay = Text(Point(150, 375), textstring)
overlay.setFace("courier")
overlay.setFill("red")
return overlay
def updateGallows(numWrongGuesses, window):
if numWrongGuesses==1:
head = Circle(Point(120,140),20)
head.draw(window)
if numWrongGuesses==2:
body = Line(Point(120,220),Point(120,160))
body.draw(window)
if numWrongGuesses==3:
arms1 = Line(Point(100,200),Point(120,160))
arms1.draw(window)
if numWrongGuesses==4:
arms2 = Line(Point(120,160),Point(140,200))
arms2.draw(window)
if numWrongGuesses==5:
leg1 = Line(Point(120,220),Point(100,250))
leg1.draw(window)
if numWrongGuesses==6:
leg2 = Line(Poin(120,220),Point(140,250))
leg2.draw(window)
def updatePuzzleDisplay(locations, letter, window):
# For each value in the locations list, print out the letter above the
# appropriate blank space.
# For each value in locations list, create a text object.
locationonspaces = 35
for index in locations:
locationonspaces = locationonspaces + 5
letterthatisguessed = Text(Point(locationonspaces, 265 ), letter)
letterthatisguessed.draw(window)
# Create text object
def getGuessLocationInPuzzle(puzzle, guess):
word = len(puzzle)
locations = []
for index in range(word):
if puzzle[index]==guess:
locations.append(index)
print guess
print index
return locations
def main():
window = GraphWin("Hangman Final", 400, 400)
drawGallows(window)
lettersToGuess = Text(Point(150, 375), "abcdefghijklmnopqrstuvwxyz")
lettersToGuess.setFace("courier")
lettersToGuess.draw(window)
guessInput = Entry(Point(250, 325), 10)
guessInput.draw(window)
puzzle = getPuzzle()
print puzzle
length = len(puzzle)
drawPuzzle(length,window)
guess = getGuess(guessInput,window)
window.getMouse()
Validguesses = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
numWrongGuesses=0
while True:
guess = getValidGuess (Validguesses,guessInput,window)
#print guess
window.getMouse
locations = getGuessLocationInPuzzle(puzzle,guess)
# print locations
if locations == []:
overlay = createTextOverlay(guess)
overlay.draw(window)
updateGallows(numWrongGuesses,window)
numWrongGuesses = numWrongGuesses + 1
else:
updatePuzzleDisplay(locations, guess, window)
overlay = createTextOverlay(guess)
overlay.draw(window)
if guess !=0:
Validguesses.remove(guess)
window.getMouse()
window.getMouse()
main()

TypeError: argument of type 'NoneType' is not iterable python

I keep getting this error for like 20 "if ntext[x] in dictionary:". The program converts text talk into english.
import csv
def CreateDictionary ():
fo = open("textToEnglish2014.csv" , "r")
dictonary = {}
reader = csv.reader(fo)
for row in reader:
dictionary[row[0]] = row[1]
return dictionary
def main():
dictionary = CreateDictionary()
y = "y"
while y == "y":
text = input("Enter text to which you would like conversion: ")
text = text.lower()
ntext = text.split(" ")
new_text = ""
x = 0
while x < len(ntext):
if ntext[x] in dictionary:
new_text = new_text + dictionary[ntext[x]] + " "
else:
export = export + "NF "
x += 1
print (new_text)
y = input("Continue conversion? y or q ")
main()
dictonary = {}
should be
dictionary = {}
note the spelling

Categories