简体   繁体   中英

Python - tkinter 'AttributeError: 'NoneType' object has no attribute 'xview''

I'm trying to place a scrollbar on a DISABLED Entry widget. However it keeps coming up with the error AttributeError: 'NoneType' object has no attribute 'xview' . Is it because no value is being returned or should the widget appear regardless of whether or not a value is being returned?

Below is the code for my program; I have commented out the code for the scrollbar:

from tkinter import *
from tkinter import ttk

def calculate(*args):
    try:
        value = int(binary.get(), 2)
    except ValueError:
        pass

    decimal.set(value)

root = Tk()
root.title("Binary to Decimal Converter")
root.wm_iconbitmap("python-xxl.ico")

mainframe = ttk.Frame(root, padding = "3 3 12 12")
mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)

binary = StringVar()
decimal = StringVar()

binary_entry = ttk.Entry(mainframe, width = 30, textvariable = binary)
binary_entry.grid(column = 2, row = 1, sticky = (W, E))

decimalView = ttk.Entry(mainframe, state = DISABLED, background = "gray99", width = 30, textvariable = decimal).grid(column = 2, row = 2, sticky = W)
"""scrollbar = Scrollbar(mainframe, orient = HORIZONTAL, command = decimalView.xview)
scrollbar.grid(column = 2, row = 3, sticky = (N, S, E, W))
decimalView.config(command = scrollbar.set)"""
ttk.Button(mainframe, text = "Calculate", command = calculate).grid(column = 3, row = 3, sticky = W)

ttk.Label(mainframe, text = "Binary").grid(column = 3, row = 1, sticky = W)
ttk.Label(mainframe, text = "Decimal").grid(column = 3, row = 2, sticky = W)

for child in mainframe.winfo_children():
    child.grid_configure(padx = 5, pady = 5)

binary_entry.focus()
root.bind("<Return>", calculate)

root.mainloop()

The problem is that grid returns None , not self .

So, when you do this:

decimalView = ttk.Entry(mainframe, state = DISABLED, background = "gray99", width = 30, textvariable = decimal).grid(column = 2, row = 2, sticky = W)

… you're setting decimalView to None . Which is why the error message tells you that it can't find an xview attribute on None .

And this isn't some weird quirk of Tkinter; almost every method in Python that mutates an object in any way returns None (or, sometimes, some other useful value—but never self ), from list.sort to file.write .

Just write it on two lines: construct the Entry and assign it to decimalView , and then grid it.

Besides the minor benefit of having working code, you'll also have more readable code, that doesn't scroll off the right side of the screen on StackOverflow or most text editors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM