AttributeError:Label实例没有调用方法

时间:2015-05-15 04:31:27

标签: python tkinter

我正在使用Tkinter制作测试程序,但我遇到了一些麻烦。

我正在尝试制作用户总是丢失的Rock,Paper,Scissors游戏,但我得到“Label没有调用实例”,这里是代码:

#Rock papers & scissor

import Tkinter as tk

class App(tk.Tk):

    def setLabel(self):

        entry2 = self.entry.get()   

        if entry2 == "paper":
            self.l1(App, text="Scissors, you loose!")
        elif entry2 == "Paper":
            self.l1(text="Scissors, you loose!")
        elif entry2 == "PAPER":
            self.l1(text="Scissors, you loose!")
        elif entry2 == "rock":
            self.l1(text="Paper, you loose!")
        elif entry2 == "Rock":
            self.l1(text="Paper, you loose!")
        elif entry2 == "ROCK":
            self.l1(text="Paper, you loose!")
        elif entry2 == "Scissors":
            self.l1(text="Rock, you loose!")
        elif entry2 == "scissors":
            self.l1(text="Rock, you loose!")
        elif entry2 == "SCISSORS":
            self.l1(text="Rock, you loose!")
        elif entry2 == "scissor":
            self.l1(text="Rock, you loose!")
        elif entry2 == "Scissor":
            self.l1(text="Rock, you loose!")
        elif entry2 == "SCISSOR":
            self.l1(text="Rock, you loose!")
        else:
            self.l1(text="wat")

    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.btn = tk.Button(self, text="Go!", command=self.setLabel)
        self.l1 = tk.Label(self, text="Waiting...")
        self.entry.pack()
        self.btn.pack()
        self.l1.pack()


App().mainloop()
App().minsize(300, 100)
App().title("Test")

1 个答案:

答案 0 :(得分:1)

一些问题:

  1. self.l1(text='mytext')不正确。当您将括号放在self.l1之后,您试图将该标签称为函数,但它不是函数。您必须调用该标签的config()方法。
  2. 在底部,您创建一个App对象并循环它...然后您创建另一个,另一个。创建一个,保存引用,然后使用它。
  3. 您的if分支比实际大。
  4. mainloop()来电应该在最后。
  5. 你拼错了“丢失”(是的,这很重要)。
  6. 以下修复了这些问题:

    import Tkinter as tk
    
    class App(tk.Tk):
    
        def setLabel(self):
    
            entry2 = self.entry.get().lower()
            if entry2.startswith('p'):
                self.l1.config(text="Scissors, you lose!")
            elif entry2.startswith('r'):
                self.l1.config(text="Paper, you lose!")
            elif entry2.startswith('s'):
                self.l1.config(text="Rock, you lose!")
            else:
                self.l1.config(text="wat")
    
        def __init__(self):
            tk.Tk.__init__(self)
            self.entry = tk.Entry(self)
            self.btn = tk.Button(self, text="Go!", command=self.setLabel)
            self.l1 = tk.Label(self, text="Waiting...")
            self.entry.pack()
            self.btn.pack()
            self.l1.pack()
    
    app = App()
    app.minsize(300, 100)
    app.title("Test")
    app.mainloop()