python - 字符串变量只是拒绝变成一个整数

标签 python python-3.x tkinter

我正在编写一个 python GUI 应用程序,它从用户那里获取一个条目,将其转换为一个整数,然后将该整数与 datetime 模块一起使用。但是,我遇到了一个问题,希望您能提供帮助。

我正在使用 Tkinter 构建一个包含 3 个元素的 GUI,一个输入框,一个“开始!”按钮和一个“退出”按钮。这是我的简化代码:

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,但稍后我会解决这个问题。现在当“开始!”按下按钮,它执行另一部分代码,如下所示:

numberdate = self.a.get() 

int(numberdate)

date_threshold = datetime.datetime.today() - datetime.timedelta(days=numberdate)

但是每当我运行这段代码时,python 都会向我抛出以下错误:

TypeError: unsupported type for timedelta days component: str

现在显然这意味着变量 numberdate 没有被转换成一个整数,它仍然是一个数字,但对于我的生活我无法弄清楚为什么。

我已经尝试在代码的前半部分将变量保存为 IntVar,但仍然没有成功。

我的代码中是否存在我遗漏的明显错误,或者我只是疯了?

最佳答案

转换发生了,但没有人在听。您必须将名称重新绑定(bind)到返回值:

numberdate = int(numberdate)

关于python - 字符串变量只是拒绝变成一个整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39622738/

相关文章:

python - 如何使用多个 Tkinter 复选按钮对齐列?

python打字模块: Mixin

python - 禁用控制台窗口的关闭按钮

python-3.x - 将字典作为参数传递给 RobotFramework 测试

python - Tkinter 输入字符限制

python - 无法在内部使用几何管理器包

python - 如何在 Windows8 上安装 Pygame 以使用 Python 3.3.3?

python - 如何对列表元素的值求和,哪些元素的值来自 Pandas 中的另一个数据框?

python-3.x - 如何在python3中导入cv2?

python-3.x - 将列表列表转换为字符串 pandas 数据框