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.
Related
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.
I know that you can check if the entry box is empty by checking its length. I'm having a hard time implementing it though, because my entry boxes are dynamically created and you can't traverse in all of it in a single loop.
Here is my code:
from tkinter import *
class Window(Canvas):
def __init__(self,master=None,**kwargs):
Canvas.__init__(self,master,**kwargs)
self.frame = Frame(self)
self.create_window(0,0,anchor=N+W,window=self.frame)
self.row = 1
self.input_x = []
self.input_y = []
self.x_values = []
self.y_values = []
self._init_entries()
def _init_entries(self):
x_value = Label(self.frame, text='x', font='Helvetica 10 bold').grid(row = self.row, column = 2)
y_value = Label(self.frame, text='y', font='Helvetica 10 bold').grid(row = self.row, column = 3)
self.row += 1
def add_entry(self):
def validate_int_entry(text):
if text == "":
return True
try:
value = int(text)
except ValueError:
return False
return value
vcmd_int = (root.register(validate_int_entry), "%P")
x_value = Entry(self.frame, validate = "key", validatecommand=vcmd_int, justify = RIGHT, width=10)
x_value.grid(row = self.row, column = 2)
y_value = Entry(self.frame, validate = "key", validatecommand=vcmd_int, justify = RIGHT, width=10)
y_value.grid(row = self.row, column = 3)
self.row += 1
self.input_x.append(x_value)
self.input_y.append(y_value)
def save_entry(self):
self.x_values.clear()
self.y_values.clear()
for entry in self.input_x:
x = int(entry.get())
self.x_values.append(x)
print(self.x_values)
for entry in self.input_y:
x = int(entry.get())
self.y_values.append(x)
print(self.y_values)
if __name__ == "__main__":
root = Tk()
root.resizable(0,0)
root.title('Lot')
lot = Window(root)
lot.grid(row=0,column=0)
scroll = Scrollbar(root)
scroll.grid(row=0,column=1,sticky=N+S)
lot.config(yscrollcommand = scroll.set)
scroll.config(command=lot.yview)
lot.configure(scrollregion = lot.bbox("all"), width=1000, height=500)
def add_points():
lot.add_entry()
lot.configure(scrollregion = lot.bbox("all"))
b1 = Button(root, text = "Add points", command = add_points)
b1.grid(row=1,column=0)
def get_value():
b1.destroy()
lot.save_entry()
b2 = Button(root, text = "Get value!", command = get_value)
b2.grid(row=2,column=0)
root.mainloop()
Here's the GUI example wherein the user clicked the 'Add points' button 5 times but forgot to fill one of the entry boxes.
Since I set that the entry boxes can only accept 'int', then it will throw an error. How can I show a MessageBox every time an entry box is empty (and if it's possible, can tell the user what entry box is empty)?
I have change your add_entry function before adding new row it will check the both fields if it find it empty the warning message will popup.
def add_entry(self):
for entry in self.input_x:
if entry.get() is '':
return messagebox.showwarning('Warning', 'Empty Fields')
for entry in self.input_y:
if entry.get() is '':
return messagebox.showwarning('Warning', 'Empty Fields')
def validate_int_entry(text):
if text == "":
return True
try:
value = int(text)
except ValueError:
return False
return value
vcmd_int = (root.register(validate_int_entry), "%P")
x_value = Entry(self.frame, validate = "key", validatecommand=vcmd_int, justify = RIGHT, width=10)
x_value.grid(row = self.row, column = 2)
y_value = Entry(self.frame, validate = "key", validatecommand=vcmd_int, justify = RIGHT, width=10)
y_value.grid(row = self.row, column = 3)
self.row += 1
self.input_x.append(x_value)
self.input_y.append(y_value)
So I have this code:
from tkinter import *
import re
master = Tk()
e1 = Entry(master)
def confirmit():
s = re.findall(r'\b\d+\b', e1.get())
if e1.get() == "Whoscreator":
vyvod.configure(text="Kewbin")
if e1.get() == "Whatscreatorsrealname":
vyvod.configure(text="Peťo Letec")
if e1.get() == "/give " + (what should I type here?):
vyvod.configure(text= s)
vyvod = Label(master, text="First Name")
confirmer = Button(text="Confirm", command = confirmit)
e1.pack()
vyvod.pack()
confirmer.pack()
mainloop()
I have an entry bar.
And I want this for example:
If I type in the bar /give 1000 it will type the number 1000 into Label vyvod. And I want this to work with any number i type after /give
The simplest solution is to split the string on a space, examine the first word, and do whatever is appropriate with the rest.
value = e1.get()
first, rest = value.split(" ", 1)
if first == "/give":
vyvod.configure(text=rest)
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 ]
So the code below:
Takes a given square, and if it is an X does nothing. If the square has an O in it, it changes the O to an X and autofills the square above, below, to the left, and to the right.
#openFile(filename): This function opens and prints the users txt file for paint
#input: none
#output: The file that needs to be painted
def openFile(filename):
file = open(filename, 'r')
for line in file:
print(line)
file.close()
#convertFile(filename): This function is used to convert the .txt file into a 2D arrary
#input: none
#output: none
def convertFile(filename):
empty = []
filename = open(filename, 'r')
for line in filename:
line = line.rstrip("\n")
empty.append(list(line))
return empty
#getCoordinates(x,y): This function is used to get the coordinates the user wants to pain from
#input: user coordinates.
#output: none
def getCoordinates(x, y):
coordinates = []
userInt = 0
user = []
try:
user = input("Please enter a square to fill , or q to exit: ")
user.split()
coordinates.append(int(user[0]))
coordinates.append(int(user[2]))
except ValueError:
print("Enter a valid input!")
user = input("Please enter a square to fill, or q to exit: ")
user.split()
coordinates.append(int(user[0]))
coordinates.append(int(user[2]))
return coordinates
def printGrid(grid):
for innerList in grid:
for item in innerList:
print(item, end = "")
print()
#autoFill(board, row, col): This is the heart of the program and the recursive program
# use to fill the board with x's
#input: none
#output: none
def autoFill(grid, rows, cols):
if grid[cols][rows] == "X":
return 0
else:
grid[cols][rows] = "X"
if rows > 0:
autoFill(grid, rows - 1, cols)
if rows < len(grid[cols]) - 1:
autoFill(grid, rows + 1, cols)
if cols > 0:
autoFill(grid, rows, cols - 1)
if cols < len(grid) - 1:
autoFill(grid, rows, cols + 1)
def main():
coordinates = []
empty = []
while True:
filename = input("Please enter a filename: ")
openFile(filename)
empty = convertFile(filename)
coordinates = getCoordinates(len(empty), len(empty[0]))
empty = autoFill(empty(coordinates[0], coordinates[1]))
for item in empty:
s = ""
s.join(item)
for x in item:
s += str(x)
print(s)
if user == "q":
return 0
main()
output should look like:
Please enter a filename: input.txt
OOOOOOXOOOO
OOOOOXOOOOO
OOOOXOOOOOO
XXOOXOOOOOO
XXXXOOOOOOO
OOOOOOOOOOO
Please enter a square to fill, or q to exit: 1, 1
XXXXXXXOOOO
XXXXXXOOOOO
XXXXXOOOOOO
XXXXXOOOOOO
XXXXOOOOOOO
OOOOOOOOOOO
But when i type in the coordinate points i get:
empty = autoFill(empty(coordinates[0], coordinates[1]))
TypeError: 'list' object is not callable
Any guidance in fixing this issue will be much appreciated
The particular error you're asking about is happening because you're trying to call empty (which is a list, as returned by convertFile) as if it were a function.