python - 如何将 python eval() 函数用于 tkinter 文本窗口?
问题描述
我有这段代码,它本质上创建了一个计算器。该计算器基于 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 必须是字符串、字节或代码对象
任何帮助表示赞赏,谢谢!
解决方案
正如例外所暗示的,
TypeError: eval() arg 1 must be a string, bytes or code object
您应该将字符串、字节或代码对象作为eval
参数传递。但目前您正在传递Text
小部件对象。
因此,为了按预期工作,请Text
使用get
.
evaluate = eval(text.get("1.0", tk.END))
推荐阅读
- python - Django - 创建电话审核应用程序模型的方向是否正确?
- r - 在 Shiny 中使用 reactiveFileReader() 时如何避免内存泄漏?
- spring - @Id 注释导致列表重复
- flutter - 如何在 Navigator.Pop 或 Push 中刷新状态
- oracle - 如何获取具有不同架构的表的 DDL
- flutter - 在 null 上调用了方法“jumpToDay”。[扑]
- javascript - 如何在反应 js 中获得多个选择选项?
- android - 如何以编程方式关闭画中画
- html - 您将如何重新创建 macOS Catalina 页面滚动效果
- python - gspread - 从类似数字的列中获取值作为字符串