Invalid command name error after destroying window in Tkinter - python-3.x

I am using CustomTkinter Ui library to create my school project. I have a login system that destroys the current window and creates a new window when the login is successful. However, it gives the following error.
invalid command name "140374651695040check_dpi_scaling"
while executing
"140374651695040check_dpi_scaling"
("after" script)
invalid command name "140374651691712click_animation"
while executing
"140374651691712click_animation"
("after" script)
invalid command name "140374651695744update"
while executing
"140374651695744update"
("after" script)
My code for login is
def login(self):
con=sqlite3.connect(database=r'ims.db')
cur=con.cursor()
try:
if self.uid.get()=="" or self.password.get()=="":
messagebox.showerror("Error","All fields are required",parent=self.root)
else:
cur.execute("select utype,uid from user where uid=? AND pass=?",(self.uid.get(),self.password.get()))
user=cur.fetchone()
uid=user[1]
if user==None:
messagebox.showerror("Error","Invalid username/password",parent=self.root)
elif user[0]=='Admin':
self.root.destroy()
obj=Admin(uid)
obj.mainloop()
else:
self.root.destroy()
obj=User(uid)
obj.mainloop()
except Exception as ex:
messagebox.showerror("Error",f'Error due to : {str(ex)}',parent=self.root)
I know this error happens because even though the window is destroyed different methods are still running. I had similar problem in my previous project which I fixed using after_cancel() but that time method that was running was function I had made so I knew where it was so It was easy to fix. But this time I don't know how to fix this issue, I think this issue is due to the method of CustomTkinter running even after destroying the window. Also, I am sorry for my English if you are not sure about mu qwery ask me, I will do my best to explain it.
I tried this solution but it didn't work.

I had a similar problem recently that was solved by using self.root.quit() instead of destroy()
E.G.:
try:
if self.uid.get() == "" or self.password.get() == "":
messagebox.showerror(
"Error",
"All fields are required",
parent=self.root
)
else:
cur.execute(
"select utype,uid from user where uid=? AND pass=?",
(self.uid.get(), self.password.get())
)
user = cur.fetchone()
uid = user[1]
if user is None: # editorial - use 'is' when comparing with 'None'
messagebox.showerror(
"Error","Invalid username/password",
parent=self.root
)
elif user[0] == 'Admin':
self.root.quit() # change here...
obj = Admin(uid)
obj.mainloop()
else:
self.root.quit() # ...and here
obj = User(uid)
obj.mainloop()

Related

loop to check for issues

i have this small program to assign issues to me, it works great on pycharm but when i compile it to exe with pyintaller it closes after the first run, ignoring the time.sleep and running again creating a loop to check for issues every 5 seconds.
why is that? how can i fix it?
import time
import winsound
from jira import JIRA
global lst_ignore
issue_var = ""
lst_ignore = []
def jira_login():
global user,token
user = 'user#cloud.com'
token = 'kj432hj43214YMzCyMLOe7682'
try:
options = {'server': 'https://cloud.atlassian.net'}
global jira
jira = JIRA(options=options, basic_auth=(user, token))
except Exception as e:
jira = ""
if '401' in str(e):
print("Login to JIRA failed. Check your username and password",e)
return jira
def check_issue():
jira_login()
size = 100000
start = 0 * 100000
search_query = 'status not in (Done, Closed,Canceled) and assignee is EMPTY and project = "Success" and reporter not in (57f778:f48131cb-b67d-43c7-b30d-2b58d98bd077)'
issues = jira.search_issues(search_query, start, size)
for issue in issues:
if issue not in lst_ignore:
winsound.Beep(2000, 1000)
issue.update(assignee={'accountId': '60f1d072a0de61930ad83770'})
print(issue, " : assinged to you!")
lst_ignore.append(issue)
def check():
check_issue()
time.sleep(5)
check()
if __name__ == '__main__':
check()
NEW ANSWER:___________________________________________________
(New info obtained from comment) If it says you don't have the module when running from the console, but it does from Pycharm, you probably have 2 different Interpreters. There are two steps you must take.
Using the terminal run: pip install jira
If it says it is already installed, uninstall using pip, and then reinstall.
Good Luck!
OLD ANSWER:____________________________________________________
It is hard to say. One thing I can tell you is that a recursive function is almost never a good idea.
So instead of:
def check():
check_issue()
time.sleep(5)
check()
if __name__ == '__main__':
check()
Try the following aproach:
RUNNING = True
def main():
while RUNNING:
check_issue()
time.sleep(5)
if __name__ == '__main__':
main()
After that you can implement that if some condition is met, it wil change the RUNNING constant to exit the program. Or, if it is a console-run program, then just use a keyboard-interrupt

How to avoid selenium driver closing automatically?

Before my question, it might be helpful to show you the general structure of my code:
class ItsyBitsy(object):
def __init__(self):
self.targets_a = dict() # data like url:document_summary
# filled by another function
def visit_targets_a(self):
browser = webdriver.Safari()
for url in self.targets_a.keys():
try:
browser.switch_to.new_window('tab')
browser.get(url)
time.sleep(2)
except Exception as e:
print(f'{url} FAILED: {e}')
continue
# do some automation stuff
time.sleep(2)
print('All done!')
I can then instantiate the class and call my method without any issues:
spider = ItsyBitsy()
spider.visit_targets_a()
>>> All done!
However after every tab is opened and automations are completed, the window closes without any prompt even though I do not have browser.close() or browser.exit() anywhere in my code.
My band-aid fix is calling time.sleep(9999999999999999) on the last loop, which keeps the window open indefinitely due to the Overflow Error, but it is obviously not a solution.
So, how do I stop the browser from exiting?!
Bonus points if you can educate me on why this is happening.
Thanks guys/gals!
You need to override exit and prevent 'browser.quit()' from automatically happening.
This keeps the browser open if you set teardown=False:
class ItsyBitsy(object):
def __init__(self, teardown=False):
self.teardown = teardown
self.targets_a = dict() # data like url:document_summary
# filled by another function
self.browser = webdriver.Safari()
def visit_targets_a(self):
for url in self.targets_a.keys():
try:
self.browser.switch_to.new_window('tab')
self.browser.get(url)
time.sleep(2)
except Exception as e:
print(f'{url} FAILED: {e}')
continue
# do some automation stuff
time.sleep(2)
print('All done!')
def __exit__(self, exc_type, exc_val, exc_tb):
if self.teardown:
self.browser.quit()
spider = ItsyBitsy(teardown=False)
spider.visit_targets_a()
Are you using VS Code? Half year ago I had the same problem and switching to Sublime text fixed this. This problem appers because VS Code has a bit wierd way to run python code (via extension) - it kills all processes which were created by the script when the last line of code has been excecuted.

Code runs on command prompt but not on hydrogen

I'm just beginning with programming(python3), using the information available on Internet. Right now I'm learning how to use try/except. My problem is that the code I wrote runs fine in the command prompt of windows 10, but not in the shell(Atom/Hydrogen) where it throws an error(line 6, NameError) because I didn't defined the variable "fish", I know that usually happened the other way around but I just want to understand if I'm making a mistake. The code is as follows:
>try:
>> fish = int (input("please enter your age "))
>except:
>> print("That's not a number ")
>> exit(0)
>if fish <= 15:
>> parentLicense = input ("have one of your parents have a license? (yes/no) ")
>> if parentLicense == "yes":
>>> print ("You can fish")
>> else:
>>> print("So sad, you or one of your parents need a license")
Hi Chiron and welcome to the community. The reason you are getting an undefined error is because fish can be undifined under certain circumstances in the try statement.
You should use
try:
# try stuff
except ValueError:
# do stuff when theres an error
else:
# stuff if try stuff works
else is only called if no exception is raised. I would avoid using bare except too as it can cause issues and its not good practice.

Can't find element Selenium

I am trying to fill in the forms in the Gmail creation page. But for some reason, my driver can't find the code. I've used all the options, path, id, name, class name, but nothing works
chrome_driver = './chromedriver'
driver = webdriver.Chrome(chrome_options=chrome_options, executable_path=chrome_driver)
driver.get('https://www.google.com/intl/nl/gmail/about/#')
try:
print('locating create account button')
create_account_button = driver.find_element_by_class_name('h-c-button')
except:
print("error, couldn't find create account button")
try:
create_account_button.click()
print('navigating to creation page')
except:
print('error navigating to creation page')
time.sleep(15)
first_name_form = driver.find_element_by_class_name('whsOnd zHQkBf')
(the sleep is just temporary, to make sure it loads completely, I know it's not efficient)
here's the link to the Gmail page:
https://accounts.google.com/signup/v2/webcreateaccount?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F%3Fpc%3Dtopnav-about-n-en&flowName=GlifWebSignIn&flowEntry=SignUp
This is the error I'm getting:
Exception has occurred: NoSuchElementException
Message: no such element: Unable to locate element: {"method":"css
selector","selector":".whsOnd zHQkBf"}
(Session info: chrome=81.0.4044.129)
Thank you for your help
I found your error and I have the solution for you. Let me first determine to you the problem. When you click on the 'Create New Account' a new window is opening. BUT your bot is still undestanding that you are located in the first window (in the one that you click on the first button in order to create the account). Thus, the bot is trying to see if there is a First Name input. That's why is failing. So, the solution is that you have to change the window that you want to specify. The way you can do it is written inside the code block.
CODE
from selenium import webdriver
import time
path = '/home/avionerman/Documents/stack'
driver = webdriver.Firefox(path)
driver.get('https://www.google.com/intl/nl/gmail/about/#')
try:
print('locating create account button')
create_account_button = driver.find_element_by_class_name('h-c-button')
except:
print("error, couldn't find create account button")
try:
create_account_button.click()
print('navigating to creation page')
except:
print('error navigating to creation page')
time.sleep(15)
# Keeping all the windows into the array named as handles
handles = driver.window_handles
# Keeping the size of the array in order to know how many windows are open
size = len(handles)
# Switch to the second opened window (id:1)
driver.switch_to.window(handles[1])
# Print the title of the current page in order to validate if it's the proper one
print(driver.title)
time.sleep(10)
first_name_input = driver.find_element_by_id('firstName')
first_name_input.click()
first_name_input.send_keys("WhateverYouWant")
last_name_input = driver.find_element_by_id('lastName')
last_name_input.click()
last_name_input.send_keys("WhateverYouWant2")
username_input = driver.find_element_by_id('username')
username_input.click()
username_input.send_keys('somethingAsAUsername')
pswd_input = driver.find_element_by_name('Passwd')
pswd_input.click()
pswd_input.send_keys('whateveryouwant')
pswd_conf_input = driver.find_element_by_name('ConfirmPasswd')
pswd_conf_input.click()
pswd_conf_input.send_keys('whateveryouwant')
time.sleep(20)
So, if you will go to line 21 you will see that I have some comments in order to tell you what these lines (from 21 until 31) are doing.
Also, I inserted all the needed code for you (first name, last name, et.c). You only have to locate the creation button (last one).
Note: Try to use ids in such cases and not class names (when the ids are clear and unique) as I already did for you.

Try-except bug in a while

I ran into a particularly infamous problem: I'm creating a sort of console program on Python 3.6, but when I write a command that is not 'exit' or 'shutdown', if this command is incorrect, the console enters the loop and keeps trying to execute the incorrect command by spamming in the console the error message defined with the 'except' instruction.
I tried to delete the 'try' and 'except' statement, but in this way, if the command is incorrect, the program is interrupted and the closing command is not executed.
P.S. I forgot to write that with the 'try-except' instruction, if i press enter without writing anything, the bug leaves the same.
Machine code - Start
import os
print("$ ", end="") #No end-line
console_standard_input = input()
while console_standard_input != ".shutdown":
if (console_standard_input == "exit"):
print("Shutting down machine...")
sys.exit(-1)
try:
machine_exec_script_path_complete = "Disk\{0}".format(console_standard_input)
os.system(machine_exec_script_path_complete)
except:
print("Unable to exec this function - Error")
print("")
print("$ ", end="")
#Machine code - Stop
I haven't been able to find a solution yet.
I'm not very good at Python, so I wanted to ask the help of an expert.
Try:
import os
print("$ ", end="") #No end-line
console_standard_input = input()
while console_standard_input != ".shutdown":
if(console_standard_input == "exit"):
print("Shutting down machine...")
sys.exit(-1)
try:
machine_exec_script_path_complete = "Disk\{0}".format(console_standard_input)
os.system(machine_exec_script_path_complete)
except:
print("Unable to exec this function - Error")
print("")
print("$ ", end="")
console_standard_input = input()
Explanation - if you wish to keep evaluating input - you have to put input there explicitly. Assigning input() to a variable assigns only it's value (user input), not the whole operation i.e. it doesn't force it to repeat, whenever the variable is reevaluated...

Resources