我正在寫一個python GUI應用程序,它從用戶處獲取一個條目,將其轉換爲一個整數,然後在datetime模塊中使用該整數。不過,我遇到了一個希望你可以幫忙的問題。字符串變量只是拒絕變成一個整數
我正在使用Tkinter構建一個帶有3個元素的GUI,一個輸入框,一個「GO!」按鈕和一個「退出」按鈕。這裏是我的簡化代碼:
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)
現在這似乎很簡單,我知道我已保存的變量作爲STRINGVAR但我將在稍後討論。現在當「GO!」按下按鈕,它執行的代碼的另一部分,這是如下:
numberdate = self.a.get()
int(numberdate)
date_threshold = datetime.datetime.today() - datetime.timedelta(days=numberdate)
然而,每當我運行此代碼,蟒蛇引發以下錯誤我:
TypeError: unsupported type for timedelta days component: str
現在很明顯,這意味着可變數字日期還沒有被轉換爲整數,它仍然是一個數字,但對於我的生活,我無法弄清楚爲什麼。
我已經嘗試在代碼的前半部分將變量保存爲IntVar,但仍然沒有運氣。
在我的代碼中有沒有明顯的錯誤,我錯過了,或者我只是生氣?
如果您使用'self.a.get',爲什麼使用'textvariable'?你知道'textvariable'是可選的,通常完全沒有必要嗎? –
@bryanoakley,你好,不,我不幸的是,我從我之前寫過的應用中複製了我的tkinter代碼,但沒有注意到,我的錯誤! – Ruthus99