我有这样的代码,这在本质上创建了一个计算器。计算器是基于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()函数可以提供精确的相同的错误,
类型错误:EVAL()ARG 1必须是字符串,字节或码对象
任何帮助表示赞赏,谢谢!
作为例外建议,
TypeError: eval() arg 1 must be a string, bytes or code object
你应该通过串,字节或代码对象作为参数eval
。但是目前要传递Text
部件对象。
因此,为了您预期的那样工作,使用Text
得到的get
插件的价值。
evaluate = eval(text.get("1.0", tk.END))
这是因为在eval()
你逝去的Tkinter.Text
类的实例。我想你要传递的文本框,你得到这样text.get(1.0, "end-1c")
,将返回你的内容在字符串,所以你应该做evaluate = eval(text.get(1.0, "end-1c"))
的内容的内容
与您的代码的问题是,你通过文本组件本身,而不是它的值EVAL。您应该使用.get()
方法从文本控件取值,然后才在使用.eval()
。
text
是Text
对象,而不是一个字符串,所以您不能直接传递到eval
。
您需要使用Text
得到的get
对象显示的文本,然后将它传递给eval
evaluate = eval(text.get(1.0, END))
这是因为你在你的eval函数text
是你的文本组件,你想要的其实是这个小部件内部的输入。相反text
的你可以尝试text.get("1.0","end-1c")
。
第一部分,1.0
意味着输入应该从行一个,字符零被读取。该end-1c
指读,直到达到文本框的末尾,而最后一个字符是一个断行字符。