NoneType 对象没有属性 yview

use*_*505 5 python tkinter python-2.7

首先,我想摆脱我知道这个问题的方式:Python - tkinter 'AttributeError: 'NoneType' object has no attribute 'xview''

但是,在阅读本文后,我仍然对问题所在感到困惑。我有一个使用 Tkinter 的程序。其中有两个文本框,用户可以在其中输入文本。我希望这些框可以滚动。但是,我在执行此操作时遇到问题。这是我的代码:

from Tkinter import *

def main():
    window = Tk()
    window.title("TexComp")
    window.geometry("500x500")
    window.resizable(height=FALSE,width=FALSE)

    windowBackground = '#E3DCA8'

    window.configure(bg=windowBackground)

    instruction = Label(text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.", bg=windowBackground).place(x=115, y=10)

    text1 = Text(width=25).pack(side=LEFT)
    text2 = Text(width=25).pack(side=RIGHT)

    scroll1y=Scrollbar(window, command=text1.yview).pack(side=LEFT, fill=Y, pady=65)
    scroll2y=Scrollbar(window, command=text2.yview).pack(side=RIGHT, fill=Y, pady=65)

    mainloop()

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

当我尝试运行它时,我在 scroll1y 和 scroll2y 滚动条上收到一条错误消息,指出“'NoneType' 对象没有属性 'yview'”。我不确定为什么会这样并且一直无法找到明确的答案。感谢您的时间。

小智 5

每个Tkinter 小部件的gridpackplace方法都就地工作(它们总是返回None)。这意味着,您需要在自己的线路上调用它们:

from Tkinter import *

def main():
    window = Tk()
    window.title("TexComp")
    window.geometry("500x500")
    window.resizable(height=FALSE,width=FALSE)

    windowBackground = '#E3DCA8'

    window.configure(bg=windowBackground)

    instruction = Label(text="Type or paste your text into one box,\nthen paste the text you want to compare it too\ninto the other one.", bg=windowBackground)
    instruction.place(x=115, y=10)

    text1 = Text(width=25)
    text1.pack(side=LEFT)
    text2 = Text(width=25)
    text2.pack(side=RIGHT)

    scroll1y=Scrollbar(window, command=text1.yview)
    scroll1y.pack(side=LEFT, fill=Y, pady=65)
    scroll2y=Scrollbar(window, command=text2.yview)
    scroll2y.pack(side=RIGHT, fill=Y, pady=65)

    mainloop()

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)