AttributeError:“应用程序”对象没有属性“标签”

时间:2018-11-25 20:02:53

标签: python tkinter attributeerror

我的代码给出了此错误,有人可以帮助我。当我将标签放置到rand_num()或tool()时,没关系,它会给出相同的错误。 如何赋予标签属性?

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()

编辑:我这样编辑,效果很好!

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()

更改的部件在上方 AttributeError:“应用程序”对象没有属性“标签”

1 个答案:

答案 0 :(得分:1)

您可以在self.label方法中定义tool()。该错误可能是由于您在rand_num()方法之前调用tool()方法引起的。