tkinter中Entry.get()方法报错:无法访问None类型的get成员
问题分析与修复方案
报错原因
在readFilefunction函数中,你将Entry组件的实例化与pack()布局方法写在了同一行:
ent_Filepath = tk.Entry(window, width=15).pack()
tkinter的所有布局方法(pack()、grid()、place())返回值均为None,这就导致ent_Filepath变量实际存储的是None,而非Entry组件对象。当内部嵌套的enter函数调用ent_Filepath.get()时,自然会触发Pylance的类型错误——试图对None类型调用get()成员方法。
修复代码
将组件实例化与布局操作拆分执行,先创建Entry对象并赋值给变量,再单独调用布局方法:
def readFilefunction(): clear() def enter(): path = ent_Filepath.get() readFile(path) # 拆分组件创建与布局步骤 ent_Filepath = tk.Entry(window, width=15) ent_Filepath.pack() # 同样建议拆分Button的创建与布局,避免后续操作按钮时出现同类问题 btn_Enter = tk.Button(window, command=enter, text="Enter") btn_Enter.pack()
额外注意
代码中调用的readFile函数未定义,运行时会触发NameError,请记得补充该函数的具体实现。
内容的提问来源于stack exchange,提问作者Declan Davis
相关产品推荐
相关产品推荐

