Arn*_*shn 38 python user-interface tkinter
我在类似的错误消息上看到了其他一些帖子,但找不到可以解决我的问题的解决方案.
我用TkInter稍微涉足并创建了一个非常简单的UI.该守则如下─
from tkinter import *
root = Tk()
def grabText(event):
print(entryBox.get())
entryBox = Entry(root, width=60).grid(row=2, column=1, sticky=W)
grabBtn = Button(root, text="Grab")
grabBtn.grid(row=8, column=1)
grabBtn.bind('<Button-1>', grabText)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
我启动并运行UI.当我单击Grab按钮时,我在控制台上收到以下错误:
C:\Python> python.exe myFiles\testBed.py
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python\lib\lib-tk\Tkinter.py", line 1403, in __call__
return self.func(*args)
File "myFiles\testBed.py", line 10, in grabText
if entryBox.get().strip()=="":
AttributeError: 'NoneType' object has no attribute 'get'
Run Code Online (Sandbox Code Playgroud)
错误追溯到entryBox.
我敢肯定有人可能以前处理过这个问题.任何帮助表示赞赏.
Nic*_*rry 77
的grid,pack并且place在功能Entry对象和所有其他部件的回报None.在python a().b()中,表达式的结果是任何b()返回,因此Entry(...).grid(...)将返回None.
你应该把它分成两行,如下所示:
entryBox = Entry(root, width=60)
entryBox.grid(row=2, column=1, sticky=W)
Run Code Online (Sandbox Code Playgroud)
通过这种方式,您可以将您的Entry参考文件存储起来entryBox并按照您的预期进行布局.如果您收集块中的所有grid和/或pack语句,这会产生额外的副作用,使您的布局更容易理解和维护.
版本的替代解决方案Python3.8+允许使用以下命令将所有这些内容放在一行中walrus operator:
(entryBox := Entry(root, width=60)).grid(row=2, column=1, sticky=W)
Run Code Online (Sandbox Code Playgroud)
现在entryBox将引用该Entry小部件并进行打包。
对于每行字符管理,我可以建议如下:
(var := Button(
text='fine', command=some_func, width=20, height=15, activebackground='grey'
)).grid(row=0, column=0, columnspan=0, rowspan=0, sticky='news')
Run Code Online (Sandbox Code Playgroud)
但那时不妨“正常”地这样做(如其他答案所建议的)
资料来源:
改变这一行:
entryBox=Entry(root,width=60).grid(row=2, column=1,sticky=W)
Run Code Online (Sandbox Code Playgroud)
分为以下两行:
entryBox=Entry(root,width=60)
entryBox.grid(row=2, column=1,sticky=W)
Run Code Online (Sandbox Code Playgroud)
这同样适用于grabBtn通过的方式-就像你已经正确的做grabBtn!