I found this answer in overflow and I don't know what the problem is?
Many others have asked this question but all of the answers are outdated or just give me more errors.
I need some help with highlighting keyword or change the color of them. My brain is blow up with creating tags over and over
from tkinter import *
#dictionary to hold words and colors
highlightWords = {'if': 'green',
'else': 'red'}
def highlighter(event):
''' the highlight function, called when a Key-press event occurs'''
for k,v in highlightWords.iteritems():
startIndex = '1.0'
while True:
startIndex = text.search(k, startIndex, END)
if startIndex:
endIndex = text.index('%s+%dc' % (startIndex, len(k)))
text.tag_add(k, startIndex, endIndex)
text.tag_config(k, foreground=v)
startIndex = endIndex
else:
break
root = Tk()
text = Text(root)
text.pack()
text.bind('<Control-Key-p>', highlighter)
With this code I get the following error
AttributeError: 'dict' object has no attribute 'iteritems'
Change your code to the following
from tkinter import *
#dictionary to hold words and colors
highlightWords = {'if': 'green',
'else': 'red'}
def highlighter(event):
''' the highlight function, called when a Key-press event occurs'''
for k,v in highlightWords.items():
startIndex = '1.0'
while True:
startIndex = text.search(k, startIndex, END)
if startIndex:
endIndex = text.index('%s+%dc' % (startIndex, len(k)))
text.tag_add(k, startIndex, endIndex)
text.tag_config(k, foreground=v)
startIndex = endIndex
else:
break
root = Tk()
text = Text(root)
text.pack()
text.bind('<Control-Key-p>', highlighter)
root.mainloop()
You need to use .items() rather than the outdated .iteritems()
Pressing Ctrl + P will then highlight instances of the words if/else.
Related
###Binary Search###
def search(list1,n):
l=0
u=len(list1)
print(u)
while l<=u:
mid = (l+u)//2
if list1[mid]==n:
global index1
index = mid
return True
else:
if list1[mid]<n:
l = list1[mid]
else:
u = list1[mid]
list1 = [4,7,8,12,45,99.102,702,10987,56666]
n = 12
list1.sort()
if search(list1, n):
print("Found at ",index)
else:
print("Not Found")
The error I am getting is:
line 26, in <module> if search(list1, n): line 11, in search if list1[mid]==n: IndexError: list index out of range
I am assuming your the u in your code is supposed to be the high pointer. In that case it should be initialized to len(list1) - 1 and in the end the left and right pointers should be set to l = list1[mid+1] and u = list1[mid-1]. For binary search its always easier to implement the recursive method. Find out more info here
I am building a GUI BMI Calculator app using Python and tkinter and I need some help.
Since there must be no special characters in the user given string, I want an efficient way to detect special characters in a string.
I used regex compile method as I saw online. But it did not detect all the special characters. As when I gave 165,56 instead for 165.56, it returned and error in console. Other characters like #$#!$ etc, all worked perfectly showing tkMessageBox as I programmed.
I've tried each character in string iterating through and finding if special characters are present and I even used regex compile as mentioned above but none satisfies my queries.
regex = re.compile('[#_!#$%^&*()<>?/\|}{~:]')
#assume have already got the value for h from user as 165,65
h = Entry.get(heightEntry)
if not h:
h = "0"
height = 0
elif h.isdigit() == True:
height = float(h)
elif h.isalnum() == True:
height = "None"
elif regex.search(h) == None:
for x in h:
if "." in x:
y += 1
if y >=2:
height = "None"
else:
height = float(h)
else:
height = "None"
#Check height lies between 0.5m and 3.0m or 50cm to 300cm
if not height:
print("There is no value for height to calculate")
tkMessageBox.showerror("Alert","No height value")
else:
if height == "None":
print("Invalid height value")
tkMessageBox.showerror("Alert","Invalid height value")
height = 0
elif not ((50.0<=height<=300.0) or (0.5<=height<=3.0)):
print("Invalid height value",height)
tkMessageBox.showerror("Alert","Invalid height value")
else:
if 50.0<=height<=300.0:
print("Height:",height,"cm")
else:
print("Height:",height,"m")
I expected the outcome to show the message box below height == "None"
But it showing traceback most recent call error.
You can use validatecommand to check whether the input string is a valid float. You can read this post for details.
import tkinter as tk
root = tk.Tk()
def onValidate(P):
try:
float(P)
except:
return False
return True
vcmd = (root.register(onValidate), '%P')
entry = tk.Entry(root, validate="key", validatecommand=vcmd)
entry.pack()
root.mainloop()
i am wanting to make it so it gets the input from the user and changes it but its only changing the last letter
i have many times to correct this but it doesn't work for some reason
from tkinter import *
import random
window = Tk()
window.title("Enigma Ui")
lbl = Label(window, text='''Welcome
''',font=("Comic Sans", 16))
lbl.grid(column=0, row=0)
window.geometry('350x200')
def clicked():
res = "" + txt.get()
keyword5 = ["a"]
if any(keyword in res for keyword in keyword5):
lbl.configure(text= "h")
keyword6 = ["b"]
if any(keyword in res for keyword in keyword6):
lbl.configure(text= "j")
btn = Button(window, text="Encrypt", bg="light blue", command = clicked)
btn.grid(column=20, row=30)
txt =Entry(window,width=10)
txt.grid(column=14,row=30)
window.mainloop()
i want it to take user input and change all letters not just one
The problem is in your clicked function, when you call lbl.configure() you will always return just the single letter h or j.
Here's a possible different clicked function:
def clicked():
res = "" + txt.get()
# define a dictionary to match keywords to their encrypted letter
keywords = {'a': 'h',
'b': 'j'}
new_label_value = res
# use the string replace function to encrypt matching letters in a loop
for keyword, encrypted in keywords.items():
new_label_value = new_label_value.replace(keyword, encrypted)
lbl.configure(text=new_label_value)
This will overwrite the keyword letters in a loop and return a new string.
I have a python box class. The class has width and length attributes. I'd like to have a method that prints a a representation of the box given its width and length (which I have set to 5). When I use my print_box method I get something like this: <console.Box object at 0x109b73da0.
I've read about str, but I'm not sure it applies to what I'm trying to achieve. I'm not printing a Box object I'm using the Box's attributes to govern how I print out asterisks.
Here's is my box class.
class Box():
def __init__(self, width=5, length=5):
self.width = width
self.height = length
def print_box():
for i in range(width):
for j in range(length):
if(i == 0 or i == width - 1 or j == 0 or j == length - 1):
print('*', end = ' ')
else:
print(' ', end = ' ')
>>> mybox = Box()
>>> mybox.print_box
Then a hollow box would be printed
You're not executing the function - you're just accessing it. Try mybox.print_box().
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
from tkinter import *
def mhello():
mtext = ment.get()
mLabel2 = Label(test, text=mtext).pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+10')
test.title('Test')
mlabel = Label(test, text='Time to guess').pack()
mbutton = Button(test, text='Click', command = mhello).pack()
mEntry = Entry(test, textvariable=ment).pack()
test.mainloop()
from tkinter import *
def mhello():
my_word = 'HELLO'
mtext = ment.get()
if my_word == mtext:
mLabel2 = Label(test, text='Correct').pack()
else:
mLabel2 = Label(test, text='Incorrect').pack()
return
test = Tk()
ment = StringVar()
test.geometry('450x450+500+300')
test.title('Test')
def label_1():
label_1 = Label(test, text='Hello. Welcome to my game.').pack()
def label_2():
label_2 = Label(test, text='What word am I thinking of?').pack()
button_1 = Button(test, text='Click', command = mhello).pack()
entry_1 = Entry(test, textvariable=ment).pack()
label_1()
test.after(5000, label_2)
test.mainloop()
from tkinter import *
from random import shuffle
game = Tk()
game.geometry('200x200')
game.grid()
game.title("My Game")
board = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def board_1():
board1 = []
k = 0
for i in range(3):
for j in range(3):
board1.append(Label(game, text = board[k]))
board1[k].grid(row = i, column = j)
k +=1
def board_2():
shuffle(board)
board2 = []
k = 0
for i in range(3):
for j in range(3):
board2.append(Label(game, text = board[k]))
board2[k].grid(row = i, column = j)
k +=1
board_1()
game.after(5000, board_2)
game.mainloop()
#2nd Option
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
The bit that has the Syntax Error is the 1st elif statement (2nd Option). Ignore all the code prior to this if necessary (it is there for context). Whenever I run the code it says that there is a syntax error and just positions the typing line (I don't know what it's called) at the end of the word elif.
This is a simple fix, with if else statements you need to have a closing ELSE and in this case there is not so when your program runs it sees that theres a lonely if without its else :)
if option == "1":
elif option == "2":
else:
'do something else in the program if any other value was recieved'
also a switch statement can be used here so it does not keep checking each condition and just goes straight to the correct case :D
The problem is that your block is separated from the first if-statement, where it actually belongs to. As it is, it follows the game.mainloop() statement, and adds an unexpected indentation. Try to rearrange your code like so:
if option == "1":
with open("sample.txt","r") as f:
print(f.read())
numbers = []
with open("sample2.txt","r") as f:
for i in range(9):
numbers.append(f.readline().strip())
print(numbers)
from random import randint
for i in range(9):
print(numbers[randint(0,8)])
elif option == "2":
print ("You have chosen option 2. Well Done, You Can Type! XD")
[ Rest of the code ]