Home > OS >  I am trying to get an int from entry
I am trying to get an int from entry

Time:04-04

import tkinter as tk

import math
window = tk.Tk()
label = tk.Label(text = 'Want to find a root?')
label.pack()
entry = tk.Entry(fg = 'blue')
entry.pack()
n = entry.get()
number = int(n)
answers = {}
roots = [x for x in range(2, 100)]
def search(number):
    for i in roots:
        if number > i:
                if number//i**2 != 0:
                    if number//i**2 != 1:
                         if (i**2)*(number//i**2) == number:

                            answers[i] = number//i**2

    print(answers)
search(number)
window.mainloop()

So I need to get a integer from entry and work with it as a int, but entry gives me a string with which i can't work.I can't type a int in entry because the programm doesn't start due to an error Error:number = int(n) ValueError: invalid literal for int() with base 10: ''

CodePudding user response:

You are getting the value of an Entry you created seconds ago. Of course it will be nothing! Use entry.get() when you need it, not anytime before. Put the .get() in the search function, and then call int on it.
Updated search function:

def search(number):
    number = int(entry.get())
    for i in roots:
        if number > i:
                if number//i**2 != 0:
                    if number//i**2 != 1:
                         if (i**2)*(number//i**2) == number:

                            answers[i] = number//i**2

And remove the two lines in your code that get the entry value and turn it into an int.

CodePudding user response:

The following code demonstrates that the statement number = int(n) will work as long n contains a convertible string.

Other code and comments are provided regarding the need to process any entries to the widget tk.Entry(fg='blue').

import tkinter as tk

import math

window = tk.Tk()
label = tk.Label(text='Want to find a root?')
label.pack()
entry = tk.Entry(fg='blue')
entry.pack()
n = entry.get()
# The print statement verifies that n is an empty string
print(f'{type(n)=} value{n=}')
# To make the code run without error the following statements are executed.
if n == '':
    n = '5' # provide numerical string for conversion to avoid an error later
# If the number 5 is typed into the entry box it will appear in the interface.
# However, note that no code yet exists to process the entry.

number = int(n) # will  be an error if n = '' the empty string
answers = {}
roots = [x for x in range(2, 100)]


def search(number):
    for i in roots:
        if number > i:
            if number // i ** 2 != 0:
                if number // i ** 2 != 1:
                    if (i ** 2) * (number // i ** 2) == number:
                        answers[i] = number // i ** 2

    print(answers)


search(number)
window.mainloop()

Output at program initialization

type(n)=<class 'str'> valuen=''
{}
  • Related