python - 为什么我在 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()
解决方案
如果您尝试打印 的值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()
此外,现在您应该意识到您的其他变量也是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()
推荐阅读
- android - 使用安全信息反应本机链接
- c++ - 数组旋转和删除
- python - 如何检索我的 redis 实例中的所有数据?
- c++ - 带有 setItem 的 QTableWidget 不显示数据
- android - 在 Android 中将 Google Vision API 与 ARCore 结合使用
- r - 如何保留在 Merge and Knit 期间创建的合并 Rmd 文件
- python - 从包中获取 Python 包分发版本
- php - 获取多维数组最后一个值的值
- python - 如何使这个加热我的 CPU 的脚本安全
- python - 如何在 python 中使用 pandas 分解 csv 中的一行?