Python Forum
'NoneType' object has no attribute 'get'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
'NoneType' object has no attribute 'get'
#1
I used to develop in VB 6 and am new to Python. I am finding it to be very powerful but a little difficult to debug at times. I am going through some very basic beginner tutorials on YouTube. I have the following "hello world" code but I am getting the error:

'NoneType' object has no attribute 'get'

Here is my Python code:

from tkinter import *

root = Tk()
root.configure(background='black')
e = Entry(root, text = "Message").grid(row=10, column = 5)
#how to make form black
# Creating a Label Widget
def myClick():
    myLabel1 = Label(root, text = "I clicked Encrypt!", bg='black', fg = 'white').grid(row=0, column=0)

def AnothClick():
    myLabel1 = Label(root, text = "" + e.get()).grid(row=0, column=0)
    
myLabel1 = Label(root, text="Hello World!", bg='black', fg = 'white').grid(row=0, column = 0)
myLabel2 = Label(root, text="My Name is Bob!", bg='black', fg = 'white').grid(row=1, column = 1)
myButton1 = Button(root, text ="Encrypt", command=myClick, fg="white", bg="black").grid(row=2, column = 1)
myButton2 = Button(root, text ="Decrypt",state = DISABLED, padx = 50).grid(row=3, column = 1)
myButton3 = Button(root, text ="Copy", command=AnothClick).grid(row=4, column=1)
# Shoving it onto the screen
# myLabel1.grid(row=0, column = 0)
# myLabel2.grid(row=1, column = 1)

root.mainloop()
From the example on YouTube, I was expecting that if I entered some text into the Entry (TextBox) and clicked the 'Copy' button, it would change Label1 to the text from the Entry box. Instead I got the above error.
Reply
#2
It's a bad practice to use wildcard imports. This can cause trouble down the road.

Here is an example for you to work with.

# Do the imports - It's bad practice to do wildcard imports eg( from tkinter import * )
import tkinter as tk

# define root, window, or whatever you name it
root = tk.Tk()

# Define some functions for the buttons
def my_click(arg):
    arg['text'] = 'I clicked encrypt!'
    label['bg'] = 'tomato'

def another_click(arg):
    arg['text'] = 'Another Click!'
    label['bg'] = 'skyblue'
    label['fg'] = 'navy'

def entry_text():
    # Setting conditional text. If the entry field is empty
    # set to default text, else text from entry field
    # Resetting background and foreground colors to default
    # Clear the entry field
    text = 'Default Text' if entry.get() == '' else entry.get() # Using entry get
    label['text'] = text
    label['bg'] = root.cget('bg')
    label['fg'] = 'black'
    entry.delete(0, 'end')

# Create entry widget - Best practice is to name widget then use pack or grid
# Not chain link eg label = tk.Label(root, text='text').pack() 
entry = tk.Entry(root)
entry.pack(side='top', fill='x', padx=8, pady=8)

label = tk.Label(root, text='Default Text', anchor='w', relief='ridge', padx=8)
label.pack(fill='x', pady=8, padx=8)

btn1 = tk.Button(root, text='Button 1')
btn1['command'] = lambda: my_click(label)
btn1.pack(side='left', fill='x', padx=8, pady=8)

btn2 = tk.Button(root, text='Button 2')
btn2['command'] = lambda: another_click(label)
btn2.pack(side='left', fill='x', padx=8, pady=8)

btn3 = tk.Button(root, text='Entry')
btn3['command'] = entry_text
btn3.pack(side='left', fill='x', padx=8, pady=8)

# Start the loop
root.mainloop()
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#3
You answer did help me on best practices, but it did not answer how to:

1. Have a text Entry box.
2. Enter text into the text Entry box.
3. Display the text entered into the text Entry box using .get().

The .get() is what is returning the error: 'NoneType' object has no attribute 'get'

With your example, I tried this below, but still get the same error:

import tkinter as tk
 
# define root, window, or whatever you name it
root = tk.Tk()
 
# Define some functions for the buttons
def my_click(arg):
    arg['text'] = 'I clicked encrypt!'
 
def another_click(arg):
    arg['text'] = 'Another Click!'
 
def reset():
    label['text'] = 'Default Text'
    
def copy():
    label['text'] = entry
 
# Create entry widget - Best practice is to name widget then use pack or grid
# Not chain link eg label = tk.Label(root, text='text').pack() 
entry = tk.Entry(root)
entry.pack(side='top', fill='x', padx=8, pady=8)
 
label = tk.Label(root, text='Default Text', anchor='w', relief='ridge', padx=8)
label.pack(fill='x', pady=8, padx=8)
 
btn1 = tk.Button(root, text='Button 1')
btn1['command'] = lambda: my_click(label)
btn1.pack(side='left', fill='x', padx=8, pady=8)
 
btn2 = tk.Button(root, text='Button 2')
btn2['command'] = lambda: another_click(label)
btn2.pack(side='left', fill='x', padx=8, pady=8)
 
btn3 = tk.Button(root, text='Reset')
btn3['command'] = reset
btn3.pack(side='left', fill='x', padx=8, pady=8)

btn3 = tk.Button(root, text='Copy')
btn3['command'] = copy
btn3.pack(side='left', fill='x', padx=8, pady=8)
 
# Start the loop
root.mainloop()
Reply
#4
Post entire error message, including trace.

This is your problem:
e = Entry(root, text = "Message").grid(row=10, column = 5)
Entry(root, text = "Message") returns a tkEntry widget.

.grid(row=10, column = 5) returns None

When you daisychain the two together, Entry(root, text = "Message").grid(row=10, column = 5 returns None. All of the variables you assigned to widgets are None. myLabel1 == None, myButton3 == None, and, of course, e == None.

You don't use any of those variables, other than e, so don't assign the widget to a variable. For e, I think you should do something different. You can directly get or set text from an Entry widget, but I would use a tkinter StringVar. Like this:
import tkinter as tk  # Do not use wildcard import

bg = "black"
fg = "white"


# It is convention to put functions near top.
def encrypt():
    """Functions should have a docstring saying what they do."""
    label.set("I clicked Encrypt!")


# Instead of creating new labels, change the text of the existing label.
def decrypt():
    """I am called by the copy button?"""
    label.set(entry.get())


root = tk.Tk()
root.configure(background=bg)

entry = tk.StringVar(root, "Message")  # Use this to get text from entry widget
tk.Entry(root, textvariable=entry).grid(row=10, column=5)

# Do not put multiple widgets in same grid location
label = tk.StringVar(root, "")  # Use this to set text of the label.
tk.Label(root, textvariable=label, bg=bg, fg=fg).grid(row=0, column=1)

# If you don't use a variable, don't create one.
tk.Label(root, text="Hello World!", bg=bg, fg=fg).grid(row=0, column=0)
tk.Label(root, text="My Name is Bob!", bg=bg, fg=fg).grid(row=1, column=1)
tk.Button(root, text="Encrypt", command=encrypt, fg=fg, bg=bg).grid(row=2, column=1)
tk.Button(root, text="Decrypt", state=tk.DISABLED, padx=50).grid(row=3, column=1)
tk.Button(root, text="Copy", command=decrypt).grid(row=4, column=1)

root.mainloop()
This is the code without using StringVar. Setting the entry text becomes difficult. I also removed the fg and bg setting stuff. If you want to change the window appearance, use ttk widets and themes. I repurposed the copy button to randomly change the theme for the window when clicked.
import tkinter as tk  # Do not use wildcard import
from tkinter import ttk
import random


def encrypt():
    label["text"] = "I clicked Encrypt!"


def decrypt():
    label["text"] = entry.get()


def change_theme():
    theme = random.choice(style.theme_names())
    label["text"] = theme
    style.theme_use(theme)


root = tk.Tk()
style = ttk.Style(root)

entry = ttk.Entry(root)
entry.insert(0, "Message")  # This is why you use a StringVar.
entry.grid(row=10, column=5)

label = ttk.Label(root, text="")
label.grid(row=0, column=1)

# If you don't use a variable, don't create one.
ttk.Label(root, text="Hello World!").grid(row=0, column=0)
ttk.Label(root, text="My Name is Bob!").grid(row=1, column=1)
ttk.Button(root, text="Encrypt", command=encrypt).grid(row=2, column=1)
ttk.Button(root, text="Decrypt", command=decrypt).grid(row=3, column=1)
ttk.Button(root, text="Copy", command=change_theme).grid(row=4, column=1)

root.mainloop()
Reply
#5
I rewrote the code a little. The entry field uses get
https://python-forum.io/thread-40919-pos...#pid173653
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags


Reply
#6
I changed the last button lines to:

btn4 = tk.Button(root, text='Copy')
btn4['command'] = copy
btn4.pack(side='left', fill='x', padx=8, pady=8)

but it still did not work.
Reply
#7
Thank you. That worked. Thanks everyone for explaining it and for the examples. It is helping me a lot. I am beginning to really appreciate Python for being fairly easy (bit of a learning curve for me but like every Syntax it has its ups and downs). I like that it is open source and free and anything I create in it, I feel truly belongs to me. I never felt 100% that way with Visual Studio.
Reply
#8
Better style demo. Class usage plus real encryption.
import tkinter as tk  # Do not use wildcard import
from tkinter import ttk
from string import ascii_letters


class Enigma(tk.Tk):
    """Super secret message encrytion machine."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.style = ttk.Style(self)
        themes = self.style.theme_names()
        self.style.theme_use(themes[0])
        self.plain = tk.StringVar(self, "Message...")
        self.encrypted = tk.StringVar(self, "")
        self.theme = tk.StringVar(self, themes[0])

        # Root window does not get styled.  Fill root window with ttk frame
        top_frame = ttk.Frame(self)
        top_frame.pack(expand=True, fill=tk.BOTH)

        ttk.Label(top_frame, text="Encrypted").grid(
            row=0, column=0, padx=5, pady=5, sticky="e"
        )
        ttk.Label(top_frame, text="Decrpyted").grid(
            row=1, column=0, padx=5, pady=5, sticky="e"
        )
        ttk.Label(top_frame, text="Theme").grid(
            row=2, column=0, padx=5, pady=5, sticky="e"
        )

        ttk.Entry(top_frame, textvariable=self.plain, width=30).grid(
            row=0, column=1, padx=5, pady=5, sticky="w"
        )
        ttk.Entry(top_frame, textvariable=self.encrypted, width=30).grid(
            row=1, column=1, padx=5, pady=5, sticky="w"
        )

        combobox = ttk.Combobox(top_frame, textvariable=self.theme, values=themes)
        combobox.grid(row=2, column=1, padx=5, pady=5, sticky="w")
        combobox.bind("<<ComboboxSelected>>", self.set_theme)

        # Want different grid for buttons.
        button_frame = ttk.Frame(top_frame)
        button_frame.grid(row=4, column=0, columnspan=2)
        ttk.Button(button_frame, text="Encrypt", command=self.encrypt).grid(
            row=0, column=0, padx=5, pady=5
        )
        ttk.Button(button_frame, text="Decrypt", command=self.decrypt).grid(
            row=0, column=1, padx=5, pady=5
        )

    def _secret_cipher(self, message, shift):
        """Top secret encription technique."""
        letters = []
        for letter in message:
            if letter in ascii_letters:
                index = (ascii_letters.index(letter) + shift) % len(ascii_letters)
                letters.append(ascii_letters[index])
            else:
                letters.append(letter)
        return "".join(letters)

    def encrypt(self):
        """Apply secret cipher to message."""
        self.encrypted.set(self._secret_cipher(self.plain.get(), 4))

    def decrypt(self):
        """Decyphter encripted message."""
        self.plain.set(self._secret_cipher(self.encrypted.get(), -4))

    def set_theme(self, event):
        """Change window theme to selected."""
        self.style.theme_use(self.theme.get())


Enigma().mainloop()
Reply
#9
Cool! I was just playing around with Encrypt/Decrypt buttons, but this is a great demo.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  tkinter AttributeError: 'GUI' object has no attribute pfdjhfuys 3 1,586 May-18-2023, 03:30 PM
Last Post: pfdjhfuys
  [Kivy] Windows 10: AttributeError: 'WM_PenProvider' object has no attribute 'hwnd' mikepy 1 2,346 Feb-20-2023, 09:26 PM
Last Post: deanhystad
  [Tkinter] Can't update label in new tk window, object has no attribute tompranks 3 3,574 Aug-30-2022, 08:44 AM
Last Post: tompranks
  AttributeError: 'NoneType' object has no attribute 'get' George87 5 15,531 Dec-23-2021, 04:47 AM
Last Post: George87
  [PyQt] AttributeError: 'NoneType' object has no attribute 'text' speedev 9 11,476 Sep-25-2021, 06:14 PM
Last Post: Axel_Erfurt
  [Tkinter] AttributeError: '' object has no attribute 'tk' Maryan 2 14,709 Oct-29-2020, 11:57 PM
Last Post: Maryan
  [Tkinter] AttributeError: 'tuple' object has no attribute 'replace' linuxhacker 7 6,909 Aug-08-2020, 12:47 AM
Last Post: linuxhacker
  [Kivy] AttributeError: 'NoneType' object has no attribute 'bind' faszination_92 2 6,290 Apr-12-2020, 07:01 PM
Last Post: Larz60+
  AttributeError: '_tkinter.tkapp' object has no attribute 'place_forget' edphilpot 5 9,214 Dec-20-2019, 09:52 PM
Last Post: joe_momma
  [Tkinter] AttributeError: 'App' object has no attribute 'set_text' Sahil1313 6 12,100 Jun-17-2018, 05:01 AM
Last Post: woooee

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020