AttributeError: 'int'对象没有属性'get

1 投票
2 回答
26985 浏览
提问于 2025-04-17 15:13

这是代码:

def StartGame():
    root = Tk()
    root.title("Maths Quiz - Trigonometry and Pythagoras' Theorem | Start The Game")
    root.geometry("640x480")
    root.configure(background = "gray92")
    TotScore = 0
    Count = 0
    while Count < 10:
        AnswerReply = None
        WorkingArea = Text(root, width = 70, height = 10, wrap = WORD).place(x = 38, y = 100)
        n = GetRandomNumber
        Question,RealAnswer = QuestionLibrary(Opposite,Adjacent,Hypotenuse,Angle,n)
        AskQuestion = Label(root, text = Question).place(x = 38, y = 300)
        PauseButton = ttk.Button(root, text = "Pause").place(x = 380, y = 10)
        HelpButton = ttk.Button(root, text = "Help", command = helpbutton_click).place(x = 460, y = 10)
        QuitButton = ttk.Button(root, text = "Quit", command = root.destroy).place(x = 540, y = 10)
        AnswerEntry = Entry(root)
        AnswerEntry.place(x = 252, y = 375)
        SubmitButton = ttk.Button(root, text = "Submit", command = submit_answer).place(x = 276, y = 400)
        Count += 1
    root.mainloop()

这是和提交按钮一起使用的函数:

def submit_answer():
    Answer = AnswerEntry.get()
    print(Answer)
    TotScore,AnswerReply = IsAnswerCorrect(Answer,RealAnswer)
    ScoreLabel = ttk.Label(root, text = TotScore).place(x = 10, y = 10)
    AnswerReplyLabel = ttk.Label(root, text = AnswerReply).place(x = 295, y = 440)

当我点击提交按钮时,出现了这个错误:

Traceback (most recent call last):
  File "C:\Python32\lib\tkinter\__init__.py", line 1399, in __call__
    return self.func(*args)
  File "C:\Users\ANNIE\Documents\School\Computing\Project\Python\GUI Maths Quiz.py", line 178, in submit_answer
    Answer = AnswerEntry.get()
AttributeError: 'int' object has no attribute 'get'

我正在尝试制作一个问答游戏,我想通过答案输入框获取用户的输入,但它告诉我这个对象没有“get”这个属性,请帮帮我!

2 个回答

0

AnswerEntry 是一个整数,而不是一个对象,所以你不能在它上面调用那个方法。

也许你缺少对象的实例呢?

1

如果你希望 AnswerEntry = Entry(root) 这一行能影响到函数外部定义的全局变量,你需要在 StartGame() 函数内部声明它为全局变量:

global AnswerEntry
AnswerEntry = Entry(root)

在函数中给一个变量赋值会让这个变量只在这个函数内部有效。看起来你在其他地方给全局变量 AnswerEntry 赋了一个整数值,所以当你调用 AnswerEntry.get() 时,submit_answer() 就能看到这个值。

不过,最好还是避免使用全局变量。

撰写回答