我有这段代码,本质上可以创建一个计算器。计算器基于eval()函数,以评估文本字段中的输入。
from tkinter import *
tkinter = Tk()
text = Text(tkinter, font = ('Helvetica', 50), height = 2, width = 20)
text.grid(row = 0, column = 0, columnspan = 4)
def createbutton(number, name, commandname, gridx, gridy):
def commandname():
text.insert(END, number)
name = Button(tkinter, command = commandname, text = number, width =
33, height = 4)
name.grid(row = gridx, column = gridy)
createbutton('0', 'button0', 'command0', 1, 1)
createbutton('1', 'button1', 'command1', 1, 2)
createbutton('2', 'button2', 'command2', 1, 3)
createbutton('3', 'button3', 'command3', 2, 1)
createbutton('4', 'button4', 'command4', 2, 2)
createbutton('5', 'button5', 'command5', 2, 3)
createbutton('6', 'button6', 'command6', 3, 1)
createbutton('7', 'button7', 'command7', 3, 2)
createbutton('8', 'button8', 'command8', 3, 3)
createbutton('9', 'button9', 'command9', 4, 2)
createbutton('+', 'additionbutton', 'additioncommand', 4, 1)
createbutton('-', 'subtractionbutton', 'subtractioncommand', 4, 3)
createbutton('*', 'multiplicationbutton', 'multiplicationcommand', 5, 1)
createbutton('÷', 'divisionbutton', 'divisioncommand', 5, 3)
def equals():
global evaluate
evaluate = eval(text)
text.delete(1.0, END)
text.insert(END, str(evaluate))
equalbutton = Button(tkinter, command = equals, text = '=', width = 33,
height = 4)
equalbutton.grid(row = 5, column = 2)
exec()函数提供完全相同的错误,
TypeError:eval()arg 1必须是字符串,字节或代码对象
感谢您的帮助,谢谢!
答案 0 :(得分:2)
作为例外建议,
TypeError: eval() arg 1 must be a string, bytes or code object
您应该将字符串,字节或代码对象作为eval
参数传递。但是目前,您正在传递Text
小部件对象。
因此,为了按预期工作,请使用Text
从get
小部件中获取值。
evaluate = eval(text.get("1.0", tk.END))
答案 1 :(得分:1)
这是因为在eval()
类中传递了Tkinter.Text
类的实例。我认为您想传递文本框的内容,您将获得类似text.get(1.0, "end-1c")
的内容,该内容将以字符串形式返回给您,因此您应该evaluate = eval(text.get(1.0, "end-1c"))
答案 2 :(得分:0)
代码的问题是您将文本小部件本身而不是其值传递给eval。您应该使用.get()
方法从文本小部件中获取值,然后再在其上使用.eval()
。
答案 3 :(得分:0)
text
是Text
对象,而不是字符串,因此您不能将其直接传递给eval
。
您需要使用Text
获取get
对象中显示的文本,然后将其传递给eval
evaluate = eval(text.get(1.0, END))
答案 4 :(得分:0)
这是因为eval函数中的text
是“文本”窗口小部件,实际上您想要的是此窗口小部件内的输入。您可以尝试使用text
来代替text.get("1.0","end-1c")
。
第一部分1.0
表示应从第一行字符零读取输入。 end-1c
的意思是读取直到到达文本框的末尾,而没有最后一个字符(即换行符)。