首页 > 解决方案 > 如何将 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 必须是字符串、字节或代码对象

任何帮助表示赞赏,谢谢!

标签: pythontkinter

解决方案


正如例外所暗示的,

TypeError: eval() arg 1 must be a string, bytes or code object

您应该将字符串、字节或代码对象作为eval参数传递。但目前您正在传递Text小部件对象。

因此,为了按预期工作,请Text使用get.

evaluate = eval(text.get("1.0", tk.END))

推荐阅读