Python GUI程序报错'NoneType' object has no attribute 'get'如何解决?
修复'NoneType' object has no attribute 'get'错误
这个错误和Python版本完全无关,问题出在你对Tkinter控件的赋值方式上:
Tkinter的grid()布局方法返回的是None,你把控件创建和布局写在一行(比如txt1 = Entry(...).grid(...)),导致txt1、txt2、txt3这些变量存的不是Entry控件对象,而是None。当你调用txt1.get()时,自然会触发NoneType没有get属性的错误。
修复步骤:
- 拆分控件创建与布局代码:先创建控件并赋值给变量,再单独调用
grid()进行布局。 - 补充缺失的导入语句:你的代码里用到了多个Tkinter模块和
randint,需要先导入。
修复后的完整代码:
from tkinter import Tk, Label, Entry, Button, messagebox from tkinter import scrolledtext from random import randint def ButClick(): try: MinNum = int(txt1.get()) MaxNum = int(txt2.get()) Num = int(txt3.get()) except ValueError: messagebox.showerror("ValueError", "Error! Invalid numbers") else: Nums = '' if MinNum <= MaxNum: i = 0 while i < Num: numOne = randint(MinNum, MaxNum) Nums = Nums + ":" + str(numOne) i += 1 scr.insert("insert", Nums + "\n") else: messagebox.showerror("NumError!!", "Error! Invalid Numbers!") root = Tk() root.title("Random is so random :)") # 拆分控件创建与布局 lb1 = Label(root, text="Min number") lb1.grid(row=0, column=0, pady=10, padx=10) txt1 = Entry(root, width=30) txt1.grid(row=0, column=1, pady=10, padx=10) lb2 = Label(root, text="Max number") lb2.grid(row=1, column=0, pady=10, padx=10) txt2 = Entry(root, width=30) txt2.grid(row=1, column=1, pady=10, padx=10) lb3 = Label(root, text="number") lb3.grid(row=2, column=0, pady=10, padx=10) txt3 = Entry(root, width=30) txt3.grid(row=2, column=1, pady=10, padx=10) but = Button(root, width=15, height=2, text="Generate", command=ButClick) but.grid(row=3, column=0, columnspan=2, pady=10, padx=10) scr = scrolledtext.ScrolledText(root, height=10) scr.grid(row=4, column=0, columnspan=2, pady=10, padx=10) root.mainloop() # 启动窗口主循环,保证窗口正常显示
额外注意:
- 原代码缺少
root.mainloop(),这是Tkinter窗口运行的必要语句,不添加的话窗口会创建后直接关闭。 scr.insert(INSERT, ...)里的INSERT可以替换为字符串"insert",避免因未导入相关常量导致的问题。
内容的提问来源于stack exchange,提问作者Poremich
相关产品推荐
相关产品推荐

