Showing a MessageBox error whenever an entry box is empty - python-3.x

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)

Related

I need to count the number of clicks on two buttons and then a percentage list in python

I need to count the number of clicks on two buttons and then a percentage list
I have a problem with passing str (self.counter)
to 3 functions which are to divide one function by another and show it as a percentage result
self.counter = 0
def clicked():
self.counter += 1
L['text'] = 'Poprawnie: ' + str(self.counter)
self.counter2 = 0
def clicked2():
self.counter2 += 1
R['text'] = 'Niepoprawnie: ' + str(self.counter2)
def clickedSum():
a_number = str(self.counter) / str(self.counter2)
percentage = "{:.2%}".format(a_number)
print(percentage)
If this is part of a class (as it has self reference, I assume it to be), you might have to initiate your two counters in the init to avoid they will be class-variables instead of instance-variables.
like so:
def __init__(self, *args, **kwargs):
self.counter = 0
...
def clicked():
...
ok, I managed to write, I will leave it if someone has a similar problem;)
self.counter = 0
self.counter2 = 0
def clicked():
self.counter += 1
L['text'] = 'True: ' + str(self.counter)
def clicked2():
self.counter2 += 1
R['text'] = 'False: ' + str(self.counter2)
def clicked3():
S['text'] = 'All click: ' + str(self.counter / (self.counter2 + self.counter)) + '%'
S = Label(self, text="All:0%")
S.pack()
b = Button(self, text="True", padx=35, pady=10, fg="#ffffff", bg="#263942", command=lambda: [clicked(), clicked3()])
b.pack(side="right")
L = Label(self, text="True:0")
L.pack(side="right")
b2 = Button(self, text="False", padx=35, pady=10, fg="#ffffff", bg="#263942", command=lambda: [clicked2(), clicked3()])
b2.pack(side="left")
R = Label(self, text="False:0")
R.pack(side="left")

I made a Tic Tac Toe game in python 3 using tkinter, but I don't get any output when I run the code,This is my first time Thank You

import tkinter as tk
window = tk.Tk()
# Code to add widgets will go here
window.title("Tic Tac Toe Board")
window.configure(bg = "white")
theboard = ['']*10
This is the outline of all the widgets
Label1 = tk.Label(window,text ="Player 1 :")
Label1.grid(row=0,column=0)
DisplayMain = tk.Text(master =window,width = 20,height = 2, state = 'disabled')
DisplayMain.grid(row = 0, column = 1)
Entry1 = tk.Entry(master = window)
Entry1.grid(row=1,column=1)
Label2 = tk.Label(window,text ="Player 2 :")
Label2.grid(row=0,column=2)
These are all the functions that I have defined
def buttonclicked(button,board,marker,position):
board[position] = marker
button['text'] = marker
button.configure(state="disabled")
board[position] = marker
user_input = Entry1.get
def executer():
global user_input
user_input = Entry1.get()
I have defined the Buttons here
Button1 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button1,theboard,marker,1))
Button1.grid(row=2,column=0)
Button2 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button2,theboard,marker,2))
Button2.grid(row=2,column=1)
Button3 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button3,theboard,marker,3))
Button3.grid(row=2,column=2)
Button4 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button4,theboard,marker,4))
Button4.grid(row=3,column=0)
Button5 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button5,theboard,marker,5))
Button5.grid(row=3,column=1)
Button6 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button6,theboard,marker,6))
Button6.grid(row=3,column=2)
Button7 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button7,theboard,marker,7))
Button7.grid(row=4,column=0)
Button8 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button8,theboard,marker,8))
Button8.grid(row=4,column=1)
Button9 = tk.Button(window,width = 20,height = 10, text = '', command= lambda: buttonclicked(Button9,theboard,marker,9))
Button9.grid(row=4,column=2)
Button10 = tk.Button(window,width = 20,height=5, text="Click Me", command = lambda: executer())
Button10.grid(row=5,column=1)
These are the rest of the functions
#Function that takes in user input
def player_input():
'''
OUTPUT = (player1marker,player2marker)
'''
global marker
marker = str(user_input)
while marker != 'X' and marker != 'O':
DisplayMain.insert(0.0,'Welcome to Tic-Tac-Toe, Choose X or O to start playing')
player1 = marker
player2 = ''
marker = marker.upper()
if player1 == 'X':
player2 = 'O'
elif player1 == 'O':
player2 = 'X'
else:
pass
continue
return (player1,player2)
#Function that randomly pics who goes first
import random
def choose_first():
player = random.randint(1,2)
if player == 1:
return ("Player 1")
else:
return ("Player 2")
#fucntion which checks if a index position on the board is free returns boolean value
def space_check(board,position):
return board[position] == ''
def full_board_check(board):
for i in range(1,10):
if space_check(board, i):
return False
#return true if full
return True
def win_check(board, mark):
if board[1] == mark and board[2] == mark and board[3]== mark:
return True
elif board[1] == mark and board[4] == mark and board[7] == mark:
return True
elif board[1] == mark and board[5] == mark and board[9] == mark:
return True
elif board[2] == mark and board[5] == mark and board[8]== mark:
return True
elif board[7] == mark and board[5] == mark and board[3]==mark:
return True
elif board[7]== mark and board[8]== mark and board[9] == mark:
return True
elif board[9] == mark and board[6] == mark and board[3] == mark:
return True
elif board[4] == mark and board[5] == mark and board[6] == mark:
return True
else:
return False
def replay():
global DisplayMain
DisplayMain.config(state = 'normal')
DisplayMain.insert(0.0,"Do you want to play again ? ")
play_game = str(user_input)
DisplayMain.config(state = 'disabled')
return play_game.lower()[0] == 'y'
game_on_ready = True
while game_on_ready == True:
player1_marker, player2_marker = player_input()
Label1['text'] = "Player 1 :" + player1_marker
Label2['text'] = "Player 2 :" + player2_marker
#Assigning input of players to variables
DisplayMain.insert(0.0,f"Player 1 chooses {player1_marker}")
DisplayMain.insert(0.0,f"Player 2 chooses {player2_marker}")
DisplayMain.config(state='disabled')
#choosing players turn
turn = choose_first()
DisplayMain.config(state='normal')
DisplayMain.insert(0.0,f'{turn} gets to go first Are you ready to play {turn} ? Enter Yes or No ')
DisplayMain.config(state='disabled')
play_game = str(user_input)
if play_game.lower()[0] == 'y':
game_on_ready = True
else:
game_on_ready = False
This is the working of the game, I think there is a problem with this
section.As, when I run the rest of the code I don't get any errors
while game_on_ready == True :
if turn == 'Player 1':
#Check if won
if win_check(theboard,player1_marker) == True:
DisplayMain.insert(0.0,f"Player 1 ' {player1_marker} ' has won !")
game_on_ready = False
else:
#check if tie
if full_board_check(theboard) == True:
DisplayMain.insert(0.0,"The game is a DRAW")
break
else:
#switch to player 2
turn = "player 2"
else:
#Check if won
if win_check(theboard,player2_marker) == True:
DisplayMain.insert(0.0,f"Player 2 ' {player2_marker} 'has won !")
game_on_ready = False
else:
#check if tie
if full_board_check(theboard) == True:
DisplayMain.insert(0.0,"The game is a DRAW !")
break
else:
#switch to player 1
turn = "Player 1"
if not replay():
DisplayMain.insert(0.0,"Thank you for playing ! HOPE YOU HAD FUN ....")
break
window.mainloop()
#Please review the code and mention the changes that have to be made.

why is it printing only the last letter

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.

Tic-tac-toe using python tkinter

Tic-tac-toe game using python tkinter is not working correctly.
Tic-tac-toe structure is correct. I just want to change the click event.
Only button9 output shown when click to any button
Every time I click any button this output is shown
from tkinter import *
bclick = True
tk = Tk()
tk.title("Tic Tac toe")
tk.geometry("300x400")
n = 9
btns = []
def ttt(button):
global bclick
print(button)
if button["text"] == "" and bclick == True:
print("if")
button.config(text="X")
bclick = False
elif button["text"] == "" and bclick == False:
print("else")
button["text"] = "0"
bclick = True
for i in range(9):
btns.append(Button(font=('Times 20 bold'), bg='white', fg='black', height=2, width=4))
row = 1
column = 0
index = 1
print(btns)
buttons = StringVar()
for i in btns:
i.grid(row=row, column=column)
i.config(command=lambda: ttt(i))
print(i, i["command"])
column += 1
if index % 3 == 0:
row += 1
column = 0
index += 1
tk.mainloop()
Common misstake. The lambda function is using the last value assigned to i so every lambda will use i=.!button9. change the lambda function to:
i.config(command=lambda current_button=i: ttt(current_button))
which will make lambda use the value of i when the lambda was created.

Python quiz, using tkinter

from tkinter import *
import tkinter as tk
q = 0
s = -1
count = 0
correct = 0
incorrect = 0
question = ["Is this a quiz","Are you sure","Dont be","see its not a quiz"]
answer = ["yes","yes","ok","ok"]
answer_cap = ["Yes","Yes","Ok","Ok"]
root = Tk()
name = tk.Label(root,text = "GUI Quiz")
name.pack()
label = tk.Label(root,text = question[0])
label.pack()
entry = tk.Entry(root)
entry.pack()
def out():
global q,correct,incorrect,s,count
count = count + 1
ans = entry.get()
print (ans)
print (question[q])
print (answer[q])
if count < 4:
if answer[q] or answer_cap[q] == ans :
q = q + 1
entry.delete(0, END)
correct = correct + 1
label.config(text = question[q])
else:
q = q + 1
entry.delete(0, END)
incorrect = incorrect + 1
label.config(text = question[q])
else:
entry.delete(0, END)
label.config(text = "Correct: "+str(correct) + " Incorrect: "+str(incorrect))
def stop():
global q,correct,incorrect
q = 0
correct = 0
incorrect = 0
entry.delete(0, END)
label.config(text = question[0])
button = tk.Button(root,text = "Submit",command = out)
button.pack()
button_two = tk.Button(root,text = "Restart",command = stop)
button_two.pack()
root.mainloop()
nothing actually wrong with the code its just how I'm doing it. When I run module it will ask my four questions and I will give the answer, but no matter what I put it will say I got 3 correct and none wrong. Am I missing something obvious or is it how I layed out the code.
The first part of your out function should not have 'count = count + 1' because this adds one to you score regardless of weather you were right or wrong; relocate the commented code.
def out():
global q,correct,incorrect,s,count
#count = count + 1
ans = entry.get()
print (ans)
print (question[q])
print (answer[q])

Resources