How to add 'backspace' event to easygui multenterbox fileds? - python

I am using easygui multenterbox so as to give users the option to edit specific information out of data being copied. My only problem is that pressing 'backspace' results in '\b' being added to the string instead of erasing a character.
Has anybody figured out a way to add a <backspace> event to the field within the multenterbox?
I have used this event in the past on tkinter "Entry" and "Text".
sample code:
msg = "Enter name"
title = "New name"
fieldName = ['name']
newTitle= 'NewName'
fieldValue = [newName]
fieldValue = multenterbox(msg,title, fieldName,fieldValue)
# make sure that none of the fields were left blank
while 1: # do forever, until we find acceptable values and break out
if fieldValue == None:
break
errmsg = ""
# look for errors in the returned values
for i in range(len(fieldName)):
if fieldValue[i].strip() == "":
errmsg = errmsg + '"{}" is a required field.\n\n'.format(fieldName[i])
if errmsg == "":
# no problems found
print ("Reply was:", fieldValue)
break
else:
# show the box again, with the errmsg as the message
fieldValue = multenterbox(errmsg, title, fieldName, fieldValue)
The above code snippet is showing the functionality that I already have, and works. My program will open a multenterbox window with the value of NewTitle which could be edited by the user. How do I control the editable entry in the multenterbox so that it supports backspace?
Thanks,
MMH

Related

Code Processing Too Many Values in PySimpleGUI

I have been making an app which lets the users check-boxes. Depending on what boxes they check it will display different information. I decided to use PySimpleGUI for this project. I made 6 check-boxes and one text input which I want the user to be able to choose between the check-boxes and enter a title of a movie in the text input box. Depending on what check-boxes they select it will display different information based on the movie whose title was entered in the text input.
When I try to process the title value entered in the text input it process all values including the boolean values of the check-boxes. The information my code tries to process is: {0: ;'my input', 'Title': True, 'Year': False...}. I only need to process the my input/the movie title input and not the boolean values of the check-boxes.
Here is an example of my code (for reference I am also using the IMDBPY library to search for movies (which I have made work, the problem is that the id = search[0].movieID line is processing too many values.):
def run_code():
global name
while True:
event, value = window.read()
if event == 'SEARCH':
print(values)
name = str(values)[5:-2]
print('Please wait while your results load...')
search = ia.search_movie(name)
id = search[0].movieID
if values['Title'] == True:
print(movie_title)
I am trying to make my code search for the ID of the film title which would be typed by the user in an input field and than (at the bottom) and print the movie title depending if they have the title checkbox selected. At this point I just get an error saying id = search[0].movieID IndexError: list index out of range) To my understanding id = search[0].movieID is taking too many values (which it is, it is taking in all the values, input and check-boxes) I only want it to take in the text input value.
How should I spread out the values to deal with this issue?
Define keys in your sg elements. Then you can pick from values just the item that you need. For example:
def test():
layout = [[sg.Text('Movie title:'), sg.Input(key='input')],
[sg.Checkbox('Title', key='title'), sg.Checkbox('Reverse title', key='reverse')],
[sg.Button('Search', enable_events=True), sg.Cancel()]
]
window = sg.Window('My Window', layout, finalize=True)
while True:
event, values = window.read()
print(f'event = {event}, values = {values}')
if event in (sg.WINDOW_CLOSED, 'Cancel', 'Exit'):
break
if event == 'Search':
print('Searching now...')
if values['title']:
print(f'Title = {values["input"]}')
if values['reverse']:
print(f'Reverse title = {values["input"][::-1]}')
# any other action as needed
For example, when you check both the checkboxes and click on Search, you'll get
event = Search, values = {'input': 'abcde', 'title': True, 'reverse': True}
Searching now...
Title = abcde
Reverse title = edcba
Now you can be sure that you've got the right title as input by the user.
Except of this, you should check the value you get in search = ia.search_movie(name). For a title not found in the database, you'll probably get None and that's where id = search[0].movieID gets you the IndexError: list index out of range because there is no None[0]. So, you may want to add something like
if search is None:
print('Not found!')
continue

Use Python and Selenium to output text of only selected index

I'm having some trouble with creating a program that automates a checkout process. I'm using python 3 along with Selenium. The program parses through a range of dates, which are outputted on the page as available four available slots. If none are available on the current page, it will click the 'next' button and search through the next four dates. If it gets to the end of the available date ranges and finds nothing, it'll wait thirty seconds and reset and do it all over again.
I've got the majority of this done, except for two issues:
1) I'm trying to add an argument that, when included, will go beyond the base functionality (which is to simply notify the user via text using Twilio), and complete the full checkout process.
This is the python code I'm using:
def find_available(args):
dates_available = True
spaces_free = False
free_spaces = ""
while not spaces_free:
while dates_available:
time.sleep(1.5)
spots = driver.find_elements_by_css_selector('.ss-carousel-item')
for spot_index, spot in zip(range(date_range), spots):
if spot.value_of_css_property('display') != 'none':
spot.click()
available_dates = driver.find_elements_by_css_selector('.Date-slot-container')
for available_date in available_dates:
if available_date.value_of_css_property('display') != 'none':
selected_spot = available_date.find_element_by_css_selector('#slot-container-UNATTENDED')
if 'No doorstep delivery' not in selected_spot.text:
free_spaces = selected_spot.text.replace('Select a time', '').strip()
spaces_free = True
else:
print(selected_spot.text.replace('Select a time', '').strip())
if spaces_free:
print('Slots Available!')
if args.checkout:
client.messages.create(to=to_mobilenumber,
from_=from_mobilenumber,
body=free_spaces)
driver.find_element_by_xpath("//*[contains(text(), 'Soonest available')]").click()
time.sleep(1.5)
driver.find_element_by_xpath("//input[#type='submit' and #value='Continue']").click()
print('Your order has been placed!')
else:
client.messages.create(to=to_mobilenumber,
from_=from_mobilenumber,
body=free_spaces)
print('Your order time will be held for the next hour. Check your date and confirm!')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="auto-checkout")
parser.add_argument('--checkout', '-c', action='store_true',
help="Select first available slot and checkout")
args = parser.parse_args()
find_available(args)
Expected Behavior
If the program is launched using the '--checkout' or '-c' argument, then, once 'spaces-free' is set to true, it should send a text with the text within the 'free_spaces' element. It should then move on to the next phase, which would be a selecting of a radio button that contains the text 'Soonest available' (as in select the first available radio button that contains an available time slot), and then click the continue button.
Actual Behavior
The program will run, find an available time slot, then simply move on to the next days, never attempting to select a radio button and move forward in the checkout process.
What am I doing wrong?
Any help would be appreciated.
it seems to me that you never set the dates_available to False inside your while loop:
while dates_available:
time.sleep(1.5)
spots = driver.find_elements_by_css_selector('.ss-carousel-item')
for spot_index, spot in zip(range(date_range), spots):
if spot.value_of_css_property('display') != 'none':
spot.click()
available_dates = driver.find_elements_by_css_selector('.Date-slot-container')
for available_date in available_dates:
if available_date.value_of_css_property('display') != 'none':
selected_spot = available_date.find_element_by_css_selector('#slot-container-UNATTENDED')
if 'No doorstep delivery' not in selected_spot.text:
free_spaces = selected_spot.text.replace('Select a time', '').strip()
spaces_free = True
else:
print(selected_spot.text.replace('Select a time', '').strip())
So you'll never exit the while loop. If you don't want to rewrite the whole logic, you could set dates_available = False right after you set spaces_free = True. That would allow exiting the while loop, but you might need a break or two to exit the for loops too.
If you want a failsafe behavior, you should refactor your code for smaller functions and if you want only the first available something, you could just return from the function with the first available data.
Something like this maybe?
def find_available(args):
def get_a_date():
while True:
time.sleep(1.5)
spots = driver.find_elements_by_css_selector('.ss-carousel-item')
for spot_index, spot in zip(range(date_range), spots):
if spot.value_of_css_property('display') != 'none':
spot.click()
available_dates = driver.find_elements_by_css_selector('.Date-slot-container')
for available_date in available_dates:
if available_date.value_of_css_property('display') != 'none':
selected_spot = available_date.find_element_by_css_selector('#slot-container-UNATTENDED')
if 'No doorstep delivery' not in selected_spot.text:
return selected_spot.text.replace('Select a time', '').strip()
else:
print(selected_spot.text.replace('Select a time', '').strip())
free_spaces = get_a_date()
print('Slots Available!')
if args.checkout:
client.messages.create(to=to_mobilenumber,
from_=from_mobilenumber,
body=free_spaces)
driver.find_element_by_xpath("//*[contains(text(), 'Soonest available')]").click()
time.sleep(1.5)
driver.find_element_by_xpath("//input[#type='submit' and #value='Continue']").click()
print('Your order has been placed!')
else:
client.messages.create(to=to_mobilenumber,
from_=from_mobilenumber,
body=free_spaces)
print('Your order time will be held for the next hour. Check your date and confirm!')

i have created a application which contain first page as login page.I want entered emailid to every page in application

I have created a application which contain first page as login page. My question is that, I want to show the entered emailid at the time of login to every page of my application. If I declare emailid as global it throwing error. Please tell me any trick if u have.
Thank u!!!
def loginbmtool(request):
emailid=request.POST["emailid"]
password=request.POST["password"]
if(str(emailid) == "brisatechnology#gmail.com" and str(password) == "hellobrisa123"):
msg ="" +emailid
return render_to_response('admin.html',{'msg':msg})
## if(str(emailid) != "brisatechnology#gmail.com" and str(password) = "brisa123"):
## msg ="" +emailid
## return render_to_response('login.html',{'wrong_user':'wrong emailid or password'})
else:
print "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
db=validate()
flag1=db.ValidateUser_Authentication(emailid,password)
if(flag1=="true"):
msg ="" +emailid
db=Fetch()
list1=db.pendinginvoice()
list2=db.delayedpay()
countofpo=db.NewPOs()
countofinvoice=db.invoicenocount()
countofacc,m,y=db.NewAccounts()
y=" "+y
mon=int(m)
listofmnth=[]
listofmnth=['January','February','March','April','May','June','July','August','September','October','November','December']
month=listofmnth[mon-1]
expiringPO=db.ExpiringPO()
print "\ncountofpo",countofpo
print list2
print list1
print list2
return render_to_response("index.html",{'msg':msg,"month":month,"year":y,"countofacc":countofacc,"expiringPO":expiringPO,"countofinvoice":countofinvoice,"countofpo":countofpo,"list1":list1,"list2":list2,"msg":msg})
else:
return render_to_response('login.html',{'wrong_user':'emailid or password you entered is incorrect?'})
I'm not that familiar with python, but if it is for web, it must have some sort of session variable. Have you tried implementing it?
For further reading: http://webpython.codepoint.net/cgi_session

Saving/Loading lists in Python

I am new to python (and programming in general) and am making a database/register for a typical class. I wanted the user to be able to add and remove pupils from the database, I used lists primarily for this but have hit a stump.
Whenever I restart the program the list the user has modified returns back to the defualt list I specified in the code. I looked around the internet and tried to save the list onto a seperate txt file. However the txt file also goes back to the defualt every time I restart the program. I would like you to please give me a way to save the changes made to the list and keep them that way. Here is the code (it's not very good):
def menu():
print "*****************CLASS REGISTER*****************"
print "Press 1 See The List Of Pupils"
print "Press 2 To Add New Pupils"
print "Press 3 To Remove Pupils"
print "Press 0 To Quit \n"
filename = open('pupil.txt','r')
pupil = ["James Steele", "Blain Krontick", "Leeroy Jenkins", "Tanvir Choudrey"]
def see_list(x):
print x
def add_pupil(x):
print "You have chosen to add a new pupil.\n"
option = raw_input("Please type the childs name.")
x.append(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been added to the system."
return x
def delete_pupil(x):
print "You have chosen to remove a pupil.\n"
option = raw_input("Please type the childs name.")
if option in x:
x.remove(option)
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
print option, "has been removed from the system."
else:
print "That person is not in the system."
return x
one = 1
while one != 0:
menu()
option = input()
if option == 1:
see_list(pupil)
elif option == 2:
add_pupil(pupil)
elif option == 3:
delete_pupil(pupil)
elif option == 0:
break
else:
print "That is not a valible choice."
filename = open('pupil.txt','w')
filename.write('\n'.join(pupil))
filename.close()
if option == 0:
quit
Well, you just open the pupil.txt file but never read back its contents. You need something like this:
filename = open('pupil.txt', 'r')
contents = filename.read()
filename.close()
pupil = [name for name in contents.split('\n') if name]
Also, you will need to handle the case when the pupil.txt file does not exist; this can be done with a try..except block around the IO calls.
Finally, as one of the comments has mentioned above, have a look at the pickle module, which lets you store a Python object in a file in Python's internal format (which is not really readable, but saves you a lot of hassle).
Not related to your question directly, but this:
one = 1
while one != 0:
...
is silly. All you need is:
while True:
...
This is what a database is for. Use sqlite - a simple file-based database the libraries for which come bundled with python.

How to check for white space input in python

I'm very new to programming and python. I'm writing a script and I want to exit the script if the customer type a white space.
questions is how do I do it right?
This is my attempt but I think is wrong
For example
userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()
line = inf.readline()
while (userType == raw_input)
print "userType\n"
if (userType == "")
print "invalid entry, the program will terminate"
# some code to close the app
I know this is old, but this may help someone in the future. I figured out how to do this with regex. Here is my code:
import re
command = raw_input("Enter command :")
if re.search(r'[\s]', command):
print "No spaces please."
else:
print "Do your thing!"
The program you provided is not a valid python program. Because you are a beginner some small changes to you program. This should run and does what I understood what it should be.
This is only a starting point: the structure is not clear and you have to change things as you need them.
userType = raw_input('Please enter the phrase to look: ')
userType = userType.strip()
#line = inf.readline() <-- never used??
while True:
userType = raw_input()
print("userType [%s]" % userType)
if userType.isspace():
print "invalid entry, the program will terminate"
# some code to close the app
break
You could strip all whitespaces in your input and check if anything is left.
import string
userType = raw_input('Please enter the phrase to look: ')
if not userType.translate(string.maketrans('',''),string.whitespace).strip():
# proceed with your program
# Your userType is unchanged.
else:
# just whitespace, you could exit.
After applying strip to remove whitespace, use this instead:
if not len(userType):
# do something with userType
else:
# nothing was entered

Categories

Resources