Ruthus99 Ruthus99 - 6 months ago 26
Python Question

String variable just refuses to be turned into an integer

I am writing a python GUI application which takes an entry from the user, converts it into an integer, and then uses that integer with the datetime module. However I have run into a problem which hopefully you can help with.

I am using Tkinter to construct a GUI with 3 elements, an entry box, a "GO!" button, and a "quit" button. Here is my simplified code:

class MyFirstGUI:
def __init__(self, master):

numberdate = StringVar()

Label(root,text="Enter the Number of days you would like to search in").grid(row=0)
self.a = Entry(root,textvariable=numberdate )
self.a.grid(row=0, column=1)

self.close_button = Button(master, text="Close", command=master.quit)
self.close_button.grid(row=3, column=1)

self.macro_button = Button(master, text="GO!", command=self.macro)
self.macro_button.grid(row=4, column=1)

Now this seems simple enough, I know I have saved the variable as a StringVar but I will address that later. Now when the "GO!" button is pressed, it executes another portion of code, this is as follows:

numberdate = self.a.get()


date_threshold = - datetime.timedelta(days=numberdate)

However whenever I run this code, python throws the following error at me:

TypeError: unsupported type for timedelta days component: str

Now obviously this means the variable numberdate hasn't been converted into an integer, it is still a number, but for the life of me I can't work out why.

I've tried saving the variable as an IntVar in the first half of the code, but still no luck.

Is there an obvious mistake in my code that I am missing, or am I just going mad?

wim wim

The conversion happens, but nobody was listening. You have to rebind the name to the return value:

numberdate = int(numberdate)