0

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

enter image description here

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.

9
  • 2
    Initially the input is empty, you need to enter data and then trigger an event to change the input to float, I suggest you learn but about event driven programming first Commented Jan 4, 2022 at 18:49
  • So there is a way to do it? I know a bit on event driven programming because I have buttons in my code. But I don't know how to trigger a casting Commented Jan 4, 2022 at 19:15
  • @CoolCloud Can you introduce the way you would follow in an answer? Commented Jan 4, 2022 at 19:31
  • so you have a button, assign a function to command, in the function you would call get and then do the conversion Commented Jan 4, 2022 at 19:32
  • 1
    because you have to wait for an event (button press in this case), but you don't know how long will it take for the event to be triggered so as to not immediately do the action, you put it in a function which can be called later. about command, it is an argument that you give to the constructor: tk.Button(master, ..., command=func_that_gets_float) (don't call the function, you need to pass only the object) Commented Jan 4, 2022 at 19:50

2 Answers 2

3

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().

Sign up to request clarification or add additional context in comments.

12 Comments

Ironically "Not a number" shortened to "NaN" can be converted to a float
Thank you @Cool Cloud your code works fine. I still can't figure out how to make float(N) a global variable, because I need to enter a value and use it very later on in a program.
What I mean is that, from your clear explanation, I shoul wait to fill the blanck space with something so I don't get the conversion error due the fact that I have an empty string. But, this means the conversion is made inside a function, cast() in this case. I tried defining globally a=1. and writing a=float(N) inside cast(). If at the end of the program I do print(a), it immediatily prints 1.0 without waiting for the button to be clicked! This means I don't know how to program, fine. But how can I export this float(N) so, finally, I could use it???
@RobTan Basically python executes till my_window.mainloop() in a single stretch. It pauses at mainloop() till you close your application, so basically when you press the button and cast is executed, it doesnt matter because print(a) has already executed, with its initial value 1.(even then you would need global a inside cast, and the code execution is halted at mainloop(). If you really want to see it that way, then put global a inside cast and move print(a) after mainloop(). There is absolutely no need for any of this, just use float(my_entry.get()) anytime you want.
@CoolCloud The purpouse is just to exit the GUI and automatically start a program that should simulate a wavefunction, outputting with Mayavi2: is working now, thanks to your help!
|
0

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.

11 Comments

Why? It is possible to convert, but you cannot convert '' to float
I did some testing and using float("") or float("some string") will cause that error. However, float("3") is valid, it is also possible to put any string value, even "" , to float if it is done directly without the casting to float.
@JussiTamminen Thanks for your answer. I read the entire guide of tkinter on realpython and many more, but it was unclear how to use integers or floats as entries. At the same time I saw that people come around the problem with casting, I really can't understand why this doesn't work to me!!
@JussiTamminen Also I don't understand: "it is also possible to put any string value to float if it is done directly without the casting to float", what do you mean?
I mean would the code work without errors with this print(N)?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.