title: Tkinter ValueError: could not convert string to float: ''
body: <p>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</p>
  <pre><code>import tkinter as tk
  from tkinter import *
  #from tkinter import ttk
  
  my_window = tk.Tk()
  
  my_label = tk.Label(master=my_window,text=&quot;N&quot;)
  my_label.pack()
  
  my_entry = tk.Entry(master=my_window)
  my_entry.pack()
  N = my_entry.get()
  
  print(float(N))
  
  my_window.mainloop()
  </code></pre>
  <p>Very nice and simple, but I get the following message</p>
  <pre><code>ValueError: could not convert string to float: ''
  </code></pre>
  <p>I tried many possibilities, but anything worked. Any little suggestion is very much appreciated. Thanks</p>
  <p>Edit:</p>
  <p>I want to understand how to assign <code>float(N)</code> to a global variable, say <code>a</code>, so I can use it later on in the code, and I just took the code of @Cool Cloud and modified it a little</p>
  <pre><code>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=&quot;N&quot;)
  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()
  </code></pre>
  <p>The output of this is in the following image</p>
  <p><a href="https://i.stack.imgur.com/zTNbU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zTNbU.png" alt="enter image description here" /></a></p>
  <p>As you can see it directly prints <code>1.0</code> without waiting for the assignment <code>a=float(N)</code>, so my doubt is how can I actually do this assignment, to use it later in my code. Thanks</p>
  <p>P.S.: I understand that <code>print(a)</code> inside the definition of <code>cast()</code> would give correctly <code>123.0</code> in this case, but my problem is more general: I'm trying to understand how to entry an N value, making it float and &quot;propagate&quot; it to the rest of the program. My doubt is given by the fact that <code>print(a)</code> almost at the very last line of the program, and still doesn't wait for <code>cast()</code> to come in.</p>