首页 > 解决方案 > 为什么我在 tkinter 条目中使用 Insert 方法收到错误?

问题描述

我的代码很简单,但我收到此错误

回溯(最后一次调用):文件“F:/Download/PY/Timer2.py”,第 10 行,在 e1.insert(0,"5") 中 AttributeError: 'NoneType' 对象没有属性 'insert'

import tkinter
from tkinter import *

root = tkinter.Tk()
root.title(string='prova')
root.configure(background='lightgray')
lbl_title = Label(root, padx=10, text="Timer", fg='black', bg='lightgray', font='Times 24', anchor='center').grid(row=0)
lbl_time = Label(root, font="Times 38", fg='black', bg='lightgray', width=8).grid(row=1)
e1 = Entry(root,font="Times 22", fg='black', bg='white', width=6).grid(row=2, column=0)
e1.insert(0,"5")
btn_start = Button(root, text='START', bg='black', fg='white', font='Times 24').grid(row=2, column=1)
root.mainloop()

标签: pythontkintertkinter-entry

解决方案


如果您尝试打印 的值e1,您会发现它实际上是None。那是因为您在定义小部件并返回grid()之后使用了该方法。因此,您需要将它们分开。这是工作代码。Entrygrid()None

from tkinter import *

root = Tk()
root.title(string='prova')
root.configure(background='lightgray')
lbl_title = Label(root, padx=10, text="Timer", fg='black', bg='lightgray', font='Times 24', anchor='center').grid(row=0)
lbl_time = Label(root, font="Times 38", fg='black', bg='lightgray', width=8).grid(row=1)
e1 = Entry(root,font="Times 22", fg='black', bg='white', width=6) ##
e1.grid(row=2, column=0) ##
e1.insert(0,"5")
btn_start = Button(root, text='START', bg='black', fg='white', font='Times 24').grid(row=2, column=1)
root.mainloop()

在此处输入图像描述

此外,现在您应该意识到您的其他变量也是None. 这是新的正确代码。

import tkinter as tk

root = tk.Tk()
root.title(string='prova')
root.configure(background='lightgray')
tk.Label(root, padx=10, text="Timer", fg='black', bg='lightgray', font='Times 24', anchor='center').grid(row=0)
tk.Label(root, font="Times 38", fg='black', bg='lightgray', width=8).grid(row=1)
e1 = tk.Entry(root,font="Times 22", fg='black', bg='white', width=6)
e1.grid(row=2, column=0)
e1.insert(0,"5")
tk.Button(root, text='START', bg='black', fg='white', font='Times 24').grid(row=2, column=1)
root.mainloop()

推荐阅读