Configure not recognized

I am trying to make a number generator yet I ran into a problem. It doesn't recognize configure. I am kind of new to tkinter and with my beginner knowledge with python, it really made my head scratching. This is the code:

from tkinter import messagebox
import random
from tkinter import *
from tkinter import ttk

window = Tk()
window.title("Random Number Generator")
window.geometry('350x200')

title_lbl = Label(window, text="Press the button to generate!").grid(row=0, column=1)

def rannum():
    ran = random.randint(0, 10000000)
    com = ans_lbl.configure(text=ran)
    
    
btn = Button(window, text='Randomize', command=rannum).grid(row=1, column=0)

ans_lbl = Label(window, text='').grid(row=2, column=0)

window.mainloop()

This is the error I recieved :

File "C:\Users\(redacted)\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "c:\Users\(redacted)\Documents\(redacted)\(redacted)", line 15, in rannum
    com = ans_lbl.configure(text=ran)
AttributeError: 'NoneType' object has no attribute 'configure'

2 answers

  • answered 2022-01-13 04:59 Ewan Brown

    ans_lbl is being assigned the value None because when you initialized it you set it to the value of Label.grid(). What you want to do is separate the Label() and .grid() calls.

    Replace

    ans_lbl = Label(...).grid(...)

    With this:

    ans_lbl = Label(...)

    ans_lbl.grid(...)

    I've done this below, and moved the initialization of ans_lbl up beside title_lbl for readability.

    import random
    from tkinter import *
    from tkinter import ttk
    
    window = Tk()
    window.title("Random Number Generator")
    window.geometry('350x200')
    
    title_lbl = Label(window, text="Press the button to generate!").grid(row=0, column=1)
    ans_lbl = Label(window, text='')
    ans_lbl.grid(row=2, column=0)
    
    def rannum():
        ran = random.randint(0, 10000000)
        com = ans_lbl.configure(text=ran)
    
    
    btn = Button(window, text='Randomize', command=rannum).grid(row=1, column=0)
    
    
    window.mainloop()
    

  • answered 2022-01-13 05:03 Manjunath K Mayya

    Can you change your method to this and try once.

    def rannum():
        ran = random.randint(0, 10000000)
        # com = ans_lbl.configure(text=ran)
        ans_lbl = Label(window, text=ran).grid(row=2, column=0)
    

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum