gpt4 book ai didi

python - 需要帮助理解 python : 中的此错误文本

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:59 25 4
gpt4 key购买 nike

好吧,基本上我写了一个不太漂亮的 GUI,它给出了随机的简单数学问题。它就像我想要的那样工作。然而,每次我点击进入时,空闲的 Shell 都会向我吐出红色。尽管如此,就像我说的那样,它继续按照我想要的方式运行。所以我无法理解为什么我的代码的这个特定部分会导致问题。抱歉代码太长:

from tkinter import Label, Frame, Entry, Button, LEFT, RIGHT, END
from tkinter.messagebox import showinfo
import random

class Ed(Frame):
'Simple arithmetic education app'
def __init__(self,parent=None):
'constructor'
Frame.__init__(self, parent)
self.pack()
self.tries = 0
Ed.make_widgets(self)
Ed.new_problem(self)

def make_widgets(self):
'defines Ed widgets'
self.entry1 = Entry(self, width=20, bg="gray", fg ="black")
self.entry1.grid(row=0, column=0, columnspan=4)
self.entry1.pack(side = LEFT)
self.entry2 = Entry(self, width=20, bg="gray", fg ="black")
self.entry2.grid(row=2, column=2, columnspan=4)
self.entry2.pack(side = LEFT)
Button(self,text="ENTER", command=self.evaluate).pack(side = RIGHT)

def new_problem(self):
'creates new arithmetic problem'
opList = ["+", "-"]
a = random.randrange(10+1)
b = random.randrange(10+1)
op = random.choice(opList)
if b > a:
op = "+"
self.entry1.insert(END, a)
self.entry1.insert(END, op)
self.entry1.insert(END, b)


def evaluate(self):
'handles button "Enter" clicks by comparing answer in entry to correct result'
result = eval(self.entry1.get())
if result == eval(self.entry2.get()):
self.tries += 1
showinfo(title="Huzzah!", message="That's correct! Way to go! You got it in {} tries.".format(self.tries))
self.entry1.delete(0, END)
self.entry2.delete(0, END)
self.entry1.insert(END, self.new_problem())
else:
self.tries += 1
self.entry2.delete(0, END)

这是我收到的消息:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python32\lib\tkinter\__init__.py", line 1399, in __call__
return self.func(*args)
File "C:\Python32\Python shit\csc242hw4\csc242hw4.py", line 55, in evaluate
self.entry1.insert(END, self.new_problem())
File "C:\Python32\lib\tkinter\__init__.py", line 2385, in insert
self.tk.call(self._w, 'insert', index, string)
_tkinter.TclError: wrong # args: should be ".52882960.52883240 insert index text"

最佳答案

错误消息说 Tkinter 认为它得到了错误数量的参数。

进一步回顾回溯,我们看到这一行导致了错误:

File "C:\Python32\Python shit\csc242hw4\csc242hw4.py", line 55, in evaluate
self.entry1.insert(END, self.new_problem())

但这似乎是正确的参数数量!那么这是怎么回事?

问题是 self.new_problem() 返回 None。看起来 Python 的 Tkinter 包装器在参数为 None 时不会传递参数。

要解决此问题,请删除对 insert 的调用并将第 55 行更改为

self.new_problem()

这是有效的,因为您已经从 new_problem 内部调用了 self.entry.insert

关于python - 需要帮助理解 python : 中的此错误文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12879117/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com