如何修复Python Tkinter中的AttributeError:文本框无get方法
解决Tkinter文本框调用
get()时报NoneType错误 问题根源
你犯了Tkinter新手常见的错误:把组件创建和布局方法(pack()/grid()/place())链式赋值给变量。这些布局方法的返回值是None,所以inputbox实际是None,调用get()自然会触发AttributeError。
另外代码里还有两处冗余/潜在问题:
- 开头创建
root又立刻destroy()再重建,完全没必要,直接创建一次即可。 layout函数里的Label组件也用了链式赋值,后续如果要修改这些Label内容会同样遇到NoneType错误,建议统一拆分。
修复后的代码
import http.client as client from tkinter import * import json # 只创建一次主窗口 root = Tk() root.geometry('500x500') conn = client.HTTPSConnection("realstonks.p.rapidapi.com") headers = { 'X-RapidAPI-Key': "[CLASSIFIED]", 'X-RapidAPI-Host': "realstonks.p.rapidapi.com" } # 拆分组件创建与布局:先赋值,再单独pack() inputbox = Text(root, padx=40, pady=30) inputbox.pack() name = "" def layout(data_obj): vol = data_obj['total_vol'] price = data_obj['price'] percent = data_obj['change_percentage'] fg = 'gray' if percent < 0: fg = 'red' elif percent > 0: fg = 'green' # 同样拆分Label的创建与布局 title_widget = Label(root, text=name, font=("arial bold", 50), underline=True) title_widget.pack() vol_widget = Label(root, text=f"{vol} in total.", font=("arial bold", 40)) vol_widget.pack() price_widget = Label(root, text=f"{price} dollars per share.", font=("arial bold", 30)) price_widget.pack() percent_widget = Label(root, text=f"{percent}%", font=("arial bold", 20), fg=fg) percent_widget.pack() def search_function(): global name # 声明使用全局变量name,否则是局部变量 name = inputbox.get("1.0","end-1c") conn.request("GET", "/" + name.upper(), headers=headers) res = conn.getresponse() data = res.read() data_obj = json.loads(data.decode('utf-8')) layout(data_obj) # 拆分Button的创建与布局 search = Button(root, text="Search Info", background="gray", command=search_function) search.pack() root.mainloop()
关键修改点
- 拆分组件赋值与布局:所有Tkinter组件都先创建赋值给变量,再单独调用
pack(),确保变量指向组件实例而非None。 - 移除冗余窗口代码:删掉最初的
root = Tk()和root.destroy(),只保留一次窗口初始化。 - 全局变量声明:在
search_function里添加global name,确保修改的是全局name变量,让layout函数能正确显示股票名称。
错误信息解析
AttributeError: 'NoneType' object has no attribute 'get'
这条错误明确说明:你调用get()方法的对象是None,不是预期的Text组件实例,根源就是链式赋值导致变量没指向组件对象。
内容的提问来源于stack exchange,提问作者Dark Shadow
相关产品推荐
相关产品推荐

