为什么我在tkinter条目中使用Insert方法时收到错误?

2024-10-02 14:17:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码很简单,但是我收到了这个错误

Traceback (most recent call last): File "F:/Download/PY/Timer2.py", line 10, in e1.insert(0,"5") AttributeError: 'NoneType' object has no attribute '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()

Tags: importtitletkinterrootgridrowbgblack
1条回答
网友
1楼 · 发布于 2024-10-02 14:17:37

如果您试图打印e1的值,您会发现它实际上是None。这是因为您在定义了Entry小部件并且grid()返回None之后使用了grid()方法。所以,你需要把它们分开。这是工作代码。你知道吗

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()

相关问题 更多 >

    热门问题