This is what I have so far
vdcm = (self.register(self.checkForInt), '%S')
roundsNumTB = Entry(self, validate = 'key', validatecommand = vdcm)
Then the checkForInt() function is defined as so
def checkForInt(self, S):
return (S.isDigit())
The entry box is meant to take an even number, and a number only; not characters. If a character is inputted, it is rejected. This will only work once though. If a character is inputted, the next keystroke which is an input is not rejected.
If someone could tell me how to make it permanently check to make sure the string is a digit, and an even one at that, it would be appreciated.
This is the error message I get if it's any help
Exception in Tkinter callback
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
return self.func(*args)
File "[py directory]", line 101, in checkForInt
return (S.isDigit())
AttributeError: 'str' object has no attribute 'isDigit'
I think the function call is isdigit() and not isDigit(), note the capitalization difference. If you want to test that the input is an integer and is even you would have to first convert the string using int() and test:
def checkForEvenInt(self, S):
if S.isdigit():
if int(S) % 2 is 0:
return True
return False
Keep in mind that Python is quite case-sensitive, including functions. For example, here's an iPython session:
In [1]: def my_func(): return True
In [2]: my_func()
Out[2]: True
In [3]: my_Func()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-ac6a0a3aba88> in <module>()
----> 1 my_Func()
NameError: name 'my_Func' is not defined
Related
I have a litte problem because whenever i run the code print(obj) in the try/except part it throws an exception. i followed it with the debugging tool and it jumps right in the str method but i coded the str methode just for testing. Normally i thought it would jump in the repr method for normal class calls.
The code breaks right in the return command of the str() method.
I just wanted to change the output of the time.time_struct class because i need the string and the attribute represenation.
the print commands ar just for displaying the results, the block in the init statement works but in the try/Except block it doesnt.
Does anyone have an idea?
import time
class timeSelf():
def __init__(self,str):
self.obj = time.strptime(str, "%H:%M")
print(self.obj.tm_hour)
print(type(self.obj))
def __repr__(self):
return "" + self.obj.tm_hour + ":" + self.obj.tm_min
def __str__(self):
return "" + self.obj.tm_hour + ":" + self.obj.tm_min
if __name__ == "__main__":
str= "16:54"
try:
obj = timeSelf(str)
print(obj)
print(type(obj))
print(type(obj.tm_hour))
except Exception:
print("stuff happened")
pass
If you hadn't caught the exception (or if you re-raised it to see what you had caught), you would see the problem is with your definitions of __str__ and __repr__. You are attempting to combine int and "" values with +, and no automatic conversion of int to str occurs there.
Traceback (most recent call last):
File "tmp.py", line 19, in <module>
print(obj)
File "tmp.py", line 13, in __str__
return "" + self.obj.tm_hour + ":" + self.obj.tm_min
TypeError: can only concatenate str (not "int") to str
You have to be explicit:
return "" + str(self.obj.tm_hour) + ":" + str(self.obj.tm_min)
or more simply:
return f"{self.obj.tm_hour}:{self.obj.tm_min}"
f-strings do call __str__ as necessary to convert the value inside {...} to a str.
def divide(num1,num2):
try:
return num1/num2
except TypeError:
return "Please provide two integers or floats"
except ZeroDivisionError:
return "Please do not divide by zero"
If you don't supply all of the required arguments, the function is never entered, so there's no way to catch that TypeError from inside the function.
To illustrate, consider a function that immediately errors out:
>>> def func(a, b, c):
... raise Exception("inside the function")
...
Now let's call it with the required arguments:
>>> func(1, 2, 3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in func
Exception: inside the function
Here you can see from the traceback (in func) that the function was entered and the error thrown from there. However, if we call it again without the arguments:
>>> func()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: func() takes exactly 3 arguments (0 given)
Note that the traceback doesn't include in func, the error happens before entering the function body. You can only catch it outside the function:
>>> try:
... func()
... except TypeError:
... print('oh no!')
...
oh no!
For positional parameters, you have to pass the same number of arguments. You can use the default argument concept, like :
def divide(num1=1,num2=1):
try:
return num1/num2
except TypeError:
return "Please provide two integers or floats"
except ZeroDivisionError:
return "Please do not divide by zero"
You can call this function using 0,1 or 2 arguments.
Because your try/except statement is catching that exception and returning the designated message.
Try something like this:
try:
if num1 and num2:
return num1 / num2
else:
return "Please provide two numbers"
except ZeroDivisionError:
return "Please do not divide by zero"
except TypeError:
return "Please provide two integers or floats"
How can I protect in Python class methods from beeing mistakenly changed? Is there some kind of a "write protection"?
Example:
class bar():
def blob(self):
return 2
if __name__ == "__main__":
foo = bar()
print(foo.blob()) # Returns 2
foo.blob = 1 # Overwrites the method "blob" without a warning!
# foo.blob returns 1, foo.blob() is not callabele anymore :(
foo.blib = 1 # Is also possible
print(foo.blob)
print(foo.blob())
When I call this script returns:
2
1
Traceback (most recent call last):
File "blob.py", line 18, in <module>
print(foo.blob())
TypeError: 'int' object is not callable
I would prefer do get a warning.
I am making a small calculator on Python3 using tkinter. In a section, I encountered
TypeError: 'NoneType' object is not callable
This is the section where I called the function:
def key_in(event):
if (event.keysym == 'Return'):
calculate()
elif (event.keysym == 'BackSpace'):
delete() # or clear()
# elif and else statements
I did not encounter any error in calculate but I get this TypeError in delete and clear
# ERROR (TypeError)
def delete():
"""Responsive function to delete the last entered character"""
global _expression, _equation # _expression = '<expression>', _equation = tkinter.StringVar()
try:
if (_expression[-1] != ' '):
_expression = _expression[0:-1:1]
else:
_expression = _expression[0:-3:1]
except IndexError:
pass
_equation.set(_expression)
# ERROR (TypeError)
def clear():
"""Function to clear the whole *_expression*"""
global _expression, _equation
_expression = ''
_equation.set(_expression)
# NO ERROR
def calculate():
"""Enters the calculated value of the expression
to the text box while handling errors
"""
global _expression, _equation
try:
try:
# Function `evaluate` will convert and calculate the `_expression` into a python
# understandable code and function `str` will convert the result into string
_expression = str(evaluate(_expression))
_equation.set(_expression)
except ZeroDivisionError:
_equation.set('∞')
_expression = ""
except:
_equation.set("ERROR")
_expression = ""
How can I solve this?
Actual error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\SpiderMan\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "G:\Python Programs\Calculator.py", line 489, in key_in
delete()
TypeError: 'NoneType' object is not callable
I was wondering what the number following the argument stands for (In the error message; the number is 1).
I am updating PsychoPy, and it showed the error message. I have searched for a while, but I did not find any explanation about it.
def onCancel(self, event):
self.app.updater = None
self.Close()
def onFileBrowse(self, event):
self.filename = event.GetString()
def onInstall(self, event):
if self.currentSelection == self.useLatestBtn:
info = self.doAutoInstall()
else:
info = self.installZipFile(self.filename)
self.statusMessage.SetLabel(info)
self.Fit()
Traceback (most recent call last):
File "C:\Program Files (x86)\PsychoPy3\lib\site-
packages\psychopy\app\connections\updates.py", line 404, in onInstall
self.statusMessage.SetLabel(info)
TypeError: Control.SetLabel(): argument 1 has unexpected type 'int'
As #TomKarzes points out in the comments, it's just plain English: argument 1 is referring to the first argument. argument 2 would refer to the second argument and so on.