1

My code gives this error someone can help me. When I place label to the rand_num() or tool() it doesn't matter it gives same error. How can give attribute to label?

from tkinter import *
import random

class Application(object):
def __init__(self):
    self.rand_num()
    self.tool()

def tool(self):
    self.label = Label(fg="white", bg="#61380B", font="Helvetica 12 bold")
    self.label["text"] = self.list

    self.label.pack()
    self.open = Button(text='Hit', command=self.rand_num())
    self.open.pack()
    self.ok = Button(text='Exit', command=root.quit)
    self.ok.pack()

def rand_num(self):
    self.list = []
    for i in range(6):
        rand = random.randint(1, 49)
        if rand not in self.list:
            self.list.append(rand)
    self.list.sort()
    self.label["text"] = self.list


if __name__ == '__main__':
    root = Tk()
    root.geometry('300x100+500+100')
    app = Application()
    mainloop()

edit: I edited like this and work so well!

from tkinter import *
import random


class Application(object):

def __init__(self):
    self.tool() #Deleted that line

def rand_num(self):
    self.list = []
    for i in range(6):
        rand = random.randint(1, 49)
        if rand not in self.list:
            self.list.append(rand)
    self.list.sort()
    self.label["text"] = self.list

def tool(self):
    self.label = Label(text='Please enter hit', #Added 'text' attribute
                       fg="white",
                       bg="#61380B",
                       font="Helvetica 12 bold")
    #Deleted that line

    self.label.pack()
    self.open = Button(text='Hit', command=self.rand_num)
    self.open.pack()
    #self.ok = Button(text='Exit', command=root.quit)
    #self.ok.pack()




if __name__ == '__main__':
    root = Tk()
    root.geometry('300x100+500+100')
    app = Application()
    mainloop()

Changed parts are above AttributeError: 'Application' object has no attribute 'label'

1 Answer 1

1

You define self.label in the tool() method. The error is probably occuring because you call the rand_num() method before the tool() method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.