I've found it difficult to understand this problem:
Traceback (most recent call last):
opc = int(self.qtjog_entry.get())
ValueError: invalid literal for int() with base 10: ''
I'm confused because in another program without self., this is possible. Look at this:
qjogos = (int(qtjog_entry.get())) # here, python casts str to int normally.
Can someone help me? Sorry, for my English, and I'm learning programming languages now. Thanks.
I hope this simple example helps you udnerstand on your errors more.
If I say qjogos = (int(qtjog_entry.get())) at the main block, like:
from tkinter import *
root = Tk()
def click():
pass
qtjog_entry = Entry(root)
qtjog_entry.pack()
qjogos = (int(qtjog_entry.get()))
b = Button(root,text='Click me',command=click)
b.pack()
root.mainloop()
I get youre same error,
Traceback (most recent call last):
File "c:/PyProjects/Patient Data Entry/test2.py", line 11, in <module>
qjogos = (int(qtjog_entry.get()))
ValueError: invalid literal for int() with base 10: ''
But now if i say it inside of a function, like:
from tkinter import *
root = Tk()
def click():
qjogos = (int(qtjog_entry.get()))
print(qjogos)
qtjog_entry = Entry(root)
qtjog_entry.pack()
b = Button(root,text='Click me',command=click)
b.pack()
root.mainloop()
I dont get any error and the number is printed in the terminal.
What happens in the first code is that, initially when the program runs, the value of whats inside the entry box is '' (empty sting) which is not an int and hence cannot be converted to an integer using int(). So you have to enter the value then click on a button which calls the function and then gets the value which is inside the entrybox at the time you clicked the button.
I hope this is what you meant in your Q and that it clears your doubt, let me know if any more doubts. Explained it more cause you mentioned you're new to programming, cheers :D
It looks like self.qtjog_entry.get() returns an empty string; you can't use int() on an empty string. Without having more context, it's hard to tell exactly what's wrong here.
Related
It's the whole day I'm trying to solve this ridiculous problem, but without success; in this forum there is a lot of material, but usually they are enormous amounts of code and I cannot understand what's going on. On the internet they generally suggest casting but it doesn't work. To make things easy I wrote a sample code to illustrate the issues I'm having in a bigger code
import tkinter as tk
from tkinter import *
#from tkinter import ttk
my_window = tk.Tk()
my_label = tk.Label(master=my_window,text="N")
my_label.pack()
my_entry = tk.Entry(master=my_window)
my_entry.pack()
N = my_entry.get()
print(float(N))
my_window.mainloop()
Very nice and simple, but I get the following message
ValueError: could not convert string to float: ''
I tried many possibilities, but anything worked. Any little suggestion is very much appreciated. Thanks
Edit:
I want to understand how to assign float(N) to a global variable, say a, so I can use it later on in the code, and I just took the code of #Cool Cloud and modified it a little
import tkinter as tk
from tkinter import *
my_window = tk.Tk()
a=1.
def cast():
N = my_entry.get()
try: # Try to execute this
print(float(N))
a=float(N)
except ValueError: # If ValueError(meaning it is not a float) is triggered then print...
print('Not a number!')
my_label = tk.Label(master=my_window,text="N")
my_label.pack()
my_entry = tk.Entry(master=my_window)
my_entry.pack()
# N = my_entry.get() N will be empty as my_entry is empty when code is executed
Button(my_window,text='Click me to convert to
float',command=cast).pack() # A button to trigger event
print(a)
my_window.mainloop()
The output of this is in the following image
As you can see it directly prints 1.0 without waiting for the assignment a=float(N), so my doubt is how can I actually do this assignment, to use it later in my code. Thanks
P.S.: I understand that print(a) inside the definition of cast() would give correctly 123.0 in this case, but my problem is more general: I'm trying to understand how to entry an N value, making it float and "propagate" it to the rest of the program. My doubt is given by the fact that print(a) almost at the very last line of the program, and still doesn't wait for cast() to come in.
GUI programming is event driven, which means you will have to code based on events triggered. Every python code runs from top to bottom, and in this case all the code from top to bottom, outside functions, is executed. That means as soon as:
my_entry = tk.Entry(master=my_window)
my_entry.pack()
...is executed, the next line to be executed is N = my_entry.get(), and at the time of execution there is NOTHING inside the entry widget and hence N becomes empty string, and then you are trying to convert that empty string to a float, which will obviously give an error.
What you should be doing is, make a button and when you click it(event is triggered) and connect it to a function that will get the input and convert to float. So that when you click the button you have entered something onto the entry and now it is no longer empty.
import tkinter as tk
from tkinter import *
my_window = tk.Tk()
def cast():
N = my_entry.get()
try: # Try to execute this
print(float(N))
except ValueError: # If ValueError(meaning it is not a float) is triggered then print...
print('Not a number!')
my_label = tk.Label(master=my_window,text="N")
my_label.pack()
my_entry = tk.Entry(master=my_window)
my_entry.pack()
# N = my_entry.get() N will be empty as my_entry is empty when code is executed
Button(my_window,text='Click me to convert to float',command=cast).pack() # A button to trigger event
my_window.mainloop()
Another way, and an unpopular way, is to use DoubleVar() which will get() the text for you, in this case, your entry will accept any value but when you get() the value from the DoubleVar() it will raise a TclError if it is not a float.
def cast():
# Unlike before, error will be generated at get() and you dont need float()
# because if there is no error then it is guaranteed to be a float anyway
try:
N = var.get()
print(N)
except TclError: # If TclError is triggered then print...
print('Not a number!')
var = DoubleVar() # tkinter control variable
my_entry = tk.Entry(master=my_window,textvariable=var)
my_entry.pack()
Note: You can do my_entry.get() and it wont give any error even if the input is not a float, error comes only in the case of var.get().
From:https://www.geeksforgeeks.org/python-tkinter-entry-widget/
"get() : Returns the entry’s current text as a string."
I think that you can't just convert string to float.
I am new to python and I have an upcoming assignment that creates a menu that creates a function whenever the users enter the input. Here is the problem, whenever I enter a number the code shows a normal invalid option. For alphabetic input, however, it started to appear tons of errors. Does anyone know how to solve this issue
import turtle
wn = turtle.Screen()
poly = turtle.Turtle()
wn.setup(1000, 600)
poly.pensize(2)
poly.fillcolor('lightblue')
poly.penup()
poly.goto(-400, 15)
poly.pendown()
def menu():
print(' *********************************')
print('1. Draw polygons')
print('2. Draw a flower')
print('3. Exit')
task = int(input('Enter an option (1/2/3): '))
return task
def draw_shape(t, sides):
for i in range(0, sides):
t.forward(50)
t.stamp()
t.left(360 / sides)
t.forward(50)
def draw_flower(t, sides):
for i in range(0, sides):
t.left(90)
t.forward(100)
t.left(137.5)
t.forward(60)
t.left(80)
t.forward(70)
das = menu()
if das == 1:
for angle in [10, 9, 8, 7, 6, 5, 4, 3]:
poly.penup()
poly.forward(100)
poly.pendown()
poly.begin_fill()
draw_shape(poly, angle)
poly.end_fill()
elif das == 2:
poly.pencolor('cyan')
wn.bgcolor('light yellow')
poly.speed(4)
poly.penup()
poly.goto(0, 0)
poly.pendown()
draw_flower(poly, 52)
poly.forward(-100)
elif das == 3:
print('Program exists. Have a nice day')
exit()
else:
print('Invalid option')
. Draw polygons
2. Draw a flower
3. Exit
Enter an option (1/2/3): sa
Traceback (most recent call last):
File "C:/Users/jonny/PycharmProjects/untitled2/Polygon and flowers.py", line 40, in <module>
das = menu()
File "C:/Users/jonny/PycharmProjects/untitled2/Polygon and flowers.py", line 18, in menu
task = int(input('Enter an option (1/2/3): '))
ValueError: invalid literal for int() with base 10: 'sa'
Your Python interpreter is basically telling you that it cannot parse 'sa' into an int, which is to be expected right?
When prompted to enter an option, if you enter sa, input(...) returns exactly that: sa, as a string.
At that point in your script, task = int(input(...)) essentially becomes task = int('sa').
Exceptions
Now put yourself in the shoes of function int(): you receive a string, and you must return an integer.
What do you do when the input string, 'sa' for that matter, does not correctly represent an integer?
You cannot return an integer, because that would imply that you parsed the string successfully.
Returning something else than an integer would make no sense (and would be a pain to work with).
So you throw an exception: the execution flow is interrupted, and a specific kind of object, an exception, is thrown.
Exception handling
When a function throws an exception, it is interrupted: it does not finish running, it does not return anything, and the thrown exception is forwarded to the calling function. If that function decides to catch that exception (i.e. to handle it), then good, the normal execution flow can resume at that point.
If it decides not to handle the exception, then that function is interrupted too and the exception is forwarded yet again to the calling function. It continues in a similar fashion until the exception is caught, or until "no calling function is left", at which point the Python interpreter takes over, halts the execution of your script, and displays info about that exception (which is what happened in your case).
A first solution
If you're new to Python, maybe you shouldn't worry too much about handling exceptions right now. More generally, if you try to handle every possible case when it comes to user input, you're in for a wild ride.
For the sake of completeness though:
In order for your code to do what you expect, replace the das = menu() line with this:
try: # Enter a section of code where exceptions may be thrown
das = menu() # menu() may throw an exception because of the int(...) inside
except: # 'Catch' any exception that was thrown using an `except` block
das = -1 # Set a dummy, invalid value
With this code, if menu() throws an exception (when you enter sa for example), it will be caught: the try block will be interrupted, and the except block will be executed. das will receive value -1, which by the rest of your code is invalid, and thus Invalid option will be displayed. This is much better than having your whole script halted!
On the other hand, if no exception is thrown by menu(), the try block will reach its end normally, and the except block will not be executed.
A better solution
However, this is not ideal. The exception should not be handled around menu(), it should be handled around int(...) inside your menu function.
You could do this as an exercise: first handle the exception inside menu, and then try to loop over the int(input(...)) statement until a valid value is entered by the user.
There again, exception handling is not necessarily trivial and can be hard to get right, especially for beginners. So don't get frustrated if it seems like a not-so-useful overcomplication to you, there will come a point where you realize you can't go without them.
You can read more about exceptions here: https://www.w3schools.com/python/python_try_except.asp or here if you want a more comprehensive tutorial: https://docs.python.org/3/tutorial/errors.html
Hope this helps. :)
I've been having some issues with my code, you see I am a beginner at python programming and so I don't understand all the errors, So I would be quite happy for assistance down below is the code, which I have checked intensively just to find the error:
class Animal(object):
def __init__(self,legs,name):
def sleep(self,hours):
print("%s is sleeping for %d hours!" % (self.name,hours))
self.legs = legs
self.name = name
roscoe = Animal(4, "Canis Lupus Familiaris")
roscoe.name = ("Roscoe")
roscoe.sleep(4)
This is the Error:
Traceback (most recent call last):
File "class.py", line 9, in <module>
roscoe.sleep(4)
AttributeError: 'Animal' object has no attribute 'sleep'
You have a syntax error in the last line.
It should be:
roscoe.sleep(4)
instead of
roscue.sleep(4)
Giving more context since I see you're a begginner at Python. The traceback of Python interpreter (the "program" that runs Python code) tells you what happened. In this case, it says "name 'roscue' is not defined". This is usually a syntax error. Sometimes it can mean that you haven't defined that function. But in this case, it's the former.
Also, going a little bit further, you're probably going to get an error of indentation. In Python, you have to indent every block that you want to put together, either with tabs or with spaces.
Finally, think about your functions, you have to put them in order. Init is a function, and sleep is another function, so after each one you have a block. Different blocks should be indented separately. Here's how the code should look, but revise it instead of running it blindly.
class Animal(object):
def __init__(self,legs,name):
self.legs = legs
self.name = name
def sleep(self,hours):
print("%s is sleeping for %d hours!" % (self.name,hours))
roscoe = Animal(4, "Canis Lupus Familiaris")
roscoe.name = ("Roscoe")
roscoe.sleep(4)
I'm learning Python & Tkinter and following a tutorial. I'm making a program to do what I'm used to do in scripting languages such as Powershell, get a user value, and then do something with it, for starter.
I can't find any example code that looks like mine. So I'm asking for your help.
Basically, this program creates a frame with a Quit Button, an Entry widget where the user enters a value, & a OK button. Then, he presses the OK button, and the value should be printed in the python terminal.
I'm getting an error but I don't understand why. I'm following a tutorial so I'm doing it the way they show, by defining a class to create the frame, putting the buttons & text box inside it.
The function to get the user input text from the entry widget is set below, where I would put my other functions, if let's say, I would like to add functions for buttons to do a print. I managed to make the print work if the value to print is set before, but I can't get the value from the Entry Widget.
from tkinter import *
class Window:
def __init__(self, master):
self.master = master
master.title("Get a value and print it")
self.info = Label(master, text="Please write something then click ENTER")
self.info.pack()
self.ebox= Entry()
self.ebox.pack()
self.viewnumber = Button(master, text="OK", activebackground="red", command=get_int)
self.viewnumber.pack()
self.quit = Button(master, text="Quit", activebackground="blue", command=quit)
self.quit.pack()
def get_int():
intnum = ebox.get
print(intnum)
def quit():
root.quit()
root = Tk()
root.geometry("400x400")
my_gui = Window(root)
root.mainloop()
I am getting this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\USERNAME\AppData\Local\Programs\Python\Python35-32\lib\tkint
er\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\USERNAME\Desktop\pyth222184.py", line 20, in get_int
intnum = ebox.get
NameError: name 'ebox' is not defined
Thank you for your help.
Actually the problem is that ebox can't be accessed from the function. You need to use self.ebox, so that it actually references the instance variable ebox.
To see more about that, visit here.
Also, you are using self.ebox.get instead of self.ebox.get(). self.ebox.get on its own would return the raw function object of self.entry.get. To actually call the function and get the contents, use self.ebox.get().
But in order for that to work, self has to be defined. To do this, add self as the first argument in every method. When you call instance.method() Python will automatically pass instance in as self. Essentially, self lets you access the current instance.
That's right. The get_int in Class is a method, and you can not call that like a function. You'd have to call that like a method something like this
elf.viewnumber = Button(master, text="OK",bg="red",command=lambda:my_gui.get_int() )
self.viewnumber.pack()
This is an example of code that would work.
Why is python shell throwing a NameError where as windows console a ValueError?
def PrintArgs(*arg):
list = ['1','2']
for i in arg:
try:
print(list[int(i)])
except ValueError:
print('Please enter integer value')
except NameError:
print('Name Error')
if __name__ == '__main__':
PrintArgs(*sys.argv[1:])
Providing the following arguments to Windows Console gives this output:
Here is how I call the code in windows console:
C:\>C:\Python34\python C:\Users\User\Documents\PYTest\Test.py 0 a
1
Please enter integer value
Providing the following arguments to Python Shell does not display the cusom error for NameError as mentioned in the code above, but mentions the following error:
PrintArgs(0,a)
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
PrintArgs(0,a)
NameError: name 'a' is not defined
In the code example you've provided you define a list i, then you iterate over a collection called list you never initiated, and assign the values in this list to i, thus dropping the original value. I guess you only provided a part of your code, please provide a minimum working example.
If I try to reproduce your problem, I only get a type error, for iterating over a list which is not initialized.