为什么在tkinter Entry中使用插入方法会收到错误消息?

时间:2018-12-02 16:48:15

标签: python tkinter tkinter-entry

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

  

跟踪(最近一次通话最近):文件“ 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()

1 个答案:

答案 0 :(得分:1)

如果您尝试打印e1的值,您将意识到它实际上是None。这是因为在定义grid()小部件并且Entry返回grid()之后就使用了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()

enter image description here

此外,现在您应该意识到您的其他变量也是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()