Python entry input verification - python

I want to create a simple game in Python 3.8, and i need to verify an entry`s input in order to create it. Something like this:
if input.text == "":
print("Error")
but i don`t know how to do this in Python. I used to do that a lot in C# but here it s not that easy apparently.

Considering you are talking about an Entry and also have the Tag tkinter in your question I assume you want to get some user input from a tkinter Entry widget.
To get a value from a Entry widget you can use the get() method. This returns a string.
You can use a simple button command or a bind() to call a function that then checks the value of the entry field.
You can also throw in a strip() just in case the user uses a space or two without imputing anything else. This way a string of spaces still returns back as an error.
Here is a simple example:
import tkinter as tk
def check_entry():
value = entry.get().strip()
if value == '':
print('Error')
else:
print('Value is not an empty string. Now do something.')
root = tk.Tk()
entry = tk.Entry(root)
entry.pack()
tk.Button(root, text='Check Entry', command=check_entry).pack()
root.mainloop()

To get an input, you can use the input function. This will automatically return a string. Here is sample usage of this:
user_input = input("Please put your input here: ") # Get user input
if user_input == "": # Compare input to empty string
print("Error")
You can see the Python docs for more information about input.

Try with:
# get the input using the input built-in function
user_input = input("insert your input here: ")
# check the input
if user_input == "":
# raise an exception and stop the program
raise ValueError("invalid input! Empty string")

Related

Tkinter cbox doesn't change var value

So, essentially what is going on is I made a password manager that had a password generation part to it, I moved it to a windowed Tkinter program for ease of use. I got everything down except for the check box, so at first when the function was called it would give me the error that alphabet had empty length so I set alphabet equal to the list with special characters. After that I tried them with while loops, same result. (this whole code is a function inside the program that only gets ran when a button is pressed) I know I could probably fix this issue with the init but I was hoping if anyone knew an easier way without rewriting too much. Here is the edit to make the code simplified. I used it with a while loop, and got the same result as the if statement. I get the error that a is not defined in this situation.
from tkinter import *
import random
def cbox_var():
while cbox_1 == True:
a = 10
while cbox_1 == False:
a = 20
print(a)
main = Tk()
cbox_1 = Checkbutton(main, text="yes or no")
cbox_1.pack()
testbutton = Button(main,text="Test", command=cbox_var)
testbutton.pack()
main.mainloop()
To get the value of a checkbutton you must assign one of the special tkinter variables to it. You can then get the value by calling the get method on the variable.
Example:
import tkinter as tk
def cbox_var():
checked = cbox_variable.get()
print("Checked?", checked)
main = tk.Tk()
cbox_variable = tk.BooleanVar()
cbox_1 = tk.Checkbutton(main, variable=cbox_variable, text="yes or no")
cbox_1.pack()
testbutton = tk.Button(main,text="Test", command=cbox_var)
testbutton.pack()
main.mainloop()

Can't understand how to validate entry widget in tkinter

I am trying to interactively validate an entry widget in tkinter to only allow the user to enter characters in the alphabet.
I have already read a very popular thread (Interactively validating Entry widget content in tkinter) and from that I have tried to figure out my solution but I just cannot seem to get it working.
In the comments of that thread was a solution that only allowed numbers, I have used that for one area of my program and it works perfectly! Code here:
from tkinter import *
root = Tk()
def testVal(inStr,i,acttyp):
ind=int(i)
if acttyp == '1': #insert
if not inStr[ind].isdigit():
return False
return True
entry = Entry(root, validate="key")
entry['validatecommand'] = (entry.register(testVal),'%P','%i','%d')
entry.pack()
root.mainloop()
I would like a solution like this, with the only change being that it accepts letters instead of numbers. Any help appreciated
Here's the solution you're looking for:
def testVal(inStr,i,acttyp):
ind=int(i)
if acttyp == '1': #insert
if not inStr[ind].isalpha():
return False
return True
Heres some other things which might be useful:
.isdigit() tests if a string is an integer
.isalpha() tests if a string contains only letters
.isalnum() tests if a string contains only letters and numbers
.isupper() tests for uppercase
.islower() tests for lowercase
For other datatypes you can use isinstance(), for example isinstance("34.5", float) will return True
Source: https://docs.python.org/3/library/stdtypes.html

Save user input from tkinter to a variable and check its content

I have written a script simulating a card game in Python where the user decides how many cards and how many piles of cards they want to play with. This input is controlled by following code where boundary_1 and boundary_2 give upper and lower limit in an integer interval and message is the user input:
def input_check(boundary_1, message, boundary_2):
run = True
while run:
try:
user_input =int(input(message))
if boundary_1 <= user_input <= boundary_2:
run = False
return user_input
else:
print ("Incorrect Value, try again!")
run = True
except ValueError:
print ("Incorrect Value, try again!")
I now want to try and make a GUI out of this card game using tkinter and I would therefore like to know if there's any way to save the user's input to a variable that could be sent into the input_check() function above? I've read through some tutorials on tkinter and found the following code:
def printtext():
global e
string = e.get()
text.insert(INSERT, string)
from tkinter import *
root = Tk()
root.title('Name')
text = Text(root)
e = Entry(root)
e.pack()
e.focus_set()
b = Button(root,text='okay',command=printtext)
text.pack()
b.pack(side='bottom')
root.mainloop()
The following code simply prints the user's input in the Textbox, what I need is the user's input being checked by my input_check() and then have an error message printed in the Textbox or the input saved to a variable for further use if it was approved. Is there any nice way to do this?
Many thanks in advance!
The simplest solution is to make string global:
def printtext():
global e
global string
string = e.get()
text.insert(INSERT, string)
When you do that, other parts of your code can now access the value in string.
This isn't the best solution, because excessive use of global variables makes a program hard to understand. The best solution is to take an object-oriented approach where you have an "application" object, and one of the attributes of that object would be something like "self.current_string".
For an example of how I recommend you structure your program, see https://stackoverflow.com/a/17470842/7432

What is the significance of the number 4 when one feeds a callback to the show argument of a Tkinter Entry Box?

Question
Why is my random ascii character selector function outputting fours, and what is the significance of the number four in this context? Why am I not recieving an error message?
Remember, the question is not about how to solve the issue, it is about why that particular number was output.
Background and Code
I am trying to creating a basic email client. I thought that it would be cool for my password box to show random characters instead of the obvious *. So, I created a function which chose a random ascii letter.
import random
import string
def random_char():
char_select = random.randrange(52)
char_choice = string.ascii_letters[char_select]
return char_choice
When I run this in an interactive terminal, it spits out a random letter. But, when I run it through my widget
self.Password = Entry (self, show = lambda: random_char())
I am met with a bunch of fours.
Extra Credit
If you have the time, please visit my related question, How to have a Tkinter Entry box repeat a function each time a character is inputted?
The show parameter accepts a value not a callback. Tkinter is taking your callback object and trying to convert it to a string and that is what you get when you type in the Entry box.
Instead you can re-configure your Entry after you type by using binding:
def key(event):
entry.configure(show = random_char())
entry = tk.Entry (self)
entry.pack()
entry.bind("<Key>", key)
EDIT
Bryan Oakley is correct in that this will change all the characters to the same single random character as you type. Showing different random characters as you type is not the way you are supposed to use the Entry widget. You can try something like:
def key(event):
global real_password
global garbage
current_len = len(v.get())
if event.char and event.char in string.ascii_letters:
real_password += event.char
garbage += random_char()
garbage = garbage[:current_len]
v.set(garbage)
v = tk.StringVar()
real_password = ""
garbage = ""
entry = tk.Entry (self, textvariable = v)
entry.pack()
entry.bind("<KeyRelease>", key)
Of course there are lots of limitations, the last character typed is changed when the key is released not when is pressed, so you have to type fast :) , there is not control over the cursor movement keys etc. But anyway it was fun trying.

Re-keying a dictionary

So I have a Python assignment where I need to use a dictionary to hold the items of a menu, then randomly re-key and re-order the menu so that I can change the order of the menu options printed out. Here is an example of the code I have:
ChoiceOne = "Rekey Menu"
ChoiceTwo = "Quit"
menu = {'1':ChoiceOne, '2':ChoiceTwo,}
userChoice = input("Please Enter the Integer for Your Menu Choice: ")
while userChoice not in menu.keys():
print("Invalid Input")
userChoice = input("Please Enter the Integer for Your Menu Choice: ")
if menu[userChoice] == ChoiceOne:
menu = rekey(menu)
elif menu[userChoice] == ChoiceTwo:
quit()
The above code loops while the user chooses not to quit, repeatedly printing out the menu over and over again. The following is my rekey() function
def rekey(menu):
rekey = {}
keylist = random.sample(range(10), 2)
for i, item in zip(keylist, menu ):
rekey[i] = menu[item]
return rekey
My problem seems to present itself in the line where I check whether the user input for the menu option is valid or not. Initially, entering anything other than "1" or "2" will cause the program to enter the While loop until a valid input is entered. After rekeying the menu however, the line "while userChoice not in menu.keys()" is always triggered and no input is ever matched to continue the program.
I've tried to find the problem by printing out the new keys in the dictionary and checking to see if the userChoice matches any one of them, but even when I choose a valid new key, the program seems to think that nothing I enter is a valid key.
I hope I've described the problem well enough to be understood, thanks for the help in advance!!
In your first case the menu keys are strings, after the rekey they are ints. You need to do a conversion of either the keys or the user input so they match.
According to the documentation the input(x) function is equivalent to eval(raw_input(x)). This means that typing "1" at the input prompt is equivalent to typing "1" in the python interpreter, so you get the integer 1.
As SpliFF has already pointed out, you need to ensure that you're either using integer keys in your menu dictionary, or you could use string keys for the dictionary and switch to using the raw_input function to read the user's choice.

Categories

Resources