AttributeError: 'NoneType' 对象没有属性 '_root' [英] AttributeError: 'NoneType' object has no attribute '_root'

查看:79
本文介绍了AttributeError: 'NoneType' 对象没有属性 '_root'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Python 3 完全陌生,只需遵循 YouTube 上的简单练习即可.

我做错了什么?

解决方案

由于缩进,display = StringVar() 不在方法中.这意味着它在第一次定义类时被执行.在创建根窗口之前,您不能创建 StringVar 的实例.

您需要为该行及其下方的行再添加一级缩进.

I am completely new to Python 3, just following simple exercises from YouTube.

https://www.youtube.com/watch?v=nefopNkZmB4&index=3&list=PL6gx4Cwl9DGAcbMi1sH6oAMk4JHw91mC_

This is my code:

    from tkinter import *


def iCalc(source, side):
    storeObj = Frame(source, borderwidth=4, bd=4, bg="powder blue")
    storeObj.pack(side=side, expand=YES, fill=BOTH)
    return storeObj


def button(source, side, text, command=None):
    storeObj = Button(source, text=text, command=command)
    storeObj.pack(side=side, expand=YES, fill=BOTH)
    return storeObj


class app(Frame):

    def __init__(self):
        Frame.__init__(self)
        self.option_add('*Font', 'arial 20 bold')
        self.pack(expand=YES, fill=BOTH)
        self.master.title('Calculator')

    display = StringVar()
    Entry(self, relief=RIDGE, textvariable=display, justify='right', bd=30, bg="powder blue").pack(side=TOP, expand=YES,
                                                                                                   fill=BOTH)
for clearBut in (["CE"], ["C"]):
    erase = iCalc(self, TOP)
for ichar in clearBut:
    button(erase, LEFT, ichar,
           lambda storeObj=display, q=ichar: storeObj.set(''))

for NumBut in ("789/", "456*", "123-", "0.+"):
    FunctionNum = iCalc(self, TOP)
for iEquals in NumBut:
    button(FunctionNum, LEFT, iEquals,
           lambda storeObj=display, q=iEquals: storeObj.set(storeObj.get() + q))
EqualsButton = iCalc(self, TOP)
for iEquals in '=':
    if iEquals in "=":
        btniEquals = button(EqualsButton, LEFT, iEquals)
        btniEquals.bind('<ButtonRelease-1>',
                        lambda e, s=self, storeObj=display: s.calc(storeObj), '+')
else:
    btniEquals = button(EqualsButton, LEFT, iEquals,
                        lambda storeObj=display, s=' %s ' % iEquals: storeObj.set(storeObj.get() + s))


def calc(self, display):
    try:
        display.set(eval(display.get()))
    except:
        display.set("ERROR")

if __name__ == '__main__':
    app().mainloop()

I am getting error:

What am I doing wrong?

解决方案

Because of the indentation, display = StringVar() is not in a method. That means it is getting executed when the class is first defined. You cannot create an instance of StringVar until after the root window has been created.

You need to add one more level of indentation for that line, and the line below it.

这篇关于AttributeError: 'NoneType' 对象没有属性 '_root'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆