【问题标题】:Trouble executing code with the tkinter.Tk() class使用 tkinter.Tk() 类执行代码时遇到问题
【发布时间】:2019-08-28 13:43:40
【问题描述】:

我正在尝试使用 tkinter.Tk() 类从 python 执行 Tcl。我的问题是每次我尝试运行我的代码时,都会收到问题底部显示的错误

仅供参考:我的 Tcl 代码保存到文件“calc.tcl”中,我的 python 文件名为“go.py”

我的python代码是:

from tkinter import *
root=Tk()
code=open('calc.tcl').read()
root.tk.call('exec'code)
root.mainloop()

我的 Tcl 代码是:

frame .fr
pack .fr

proc calc {} {
    set text [.fr.ent1 get]
    if {[catch {set result [expr $text]}]} {
        set result "calculation failed"
    }
    .fr.ent2 delete 0 end 
    .fr.ent2 insert 1 $result
} 

entry .fr.ent1
bind .fr.ent1 <Return> {calc}
entry .fr.ent2

grid .fr.ent1 -row 0 -column 0
grid .fr.ent2 -row 1 -column 0

错误是:

Traceback (most recent call last):
  File "go.py", line 4, in <module>
    root.tk.call('exec',code)
_tkinter.TclError: couldn't execute "

frame .fr
pack .fr

proc calc {} {
    set text [.fr.ent1 get]
    if {[catch {set result [expr $text]}]} {
        set result "calculation failed"
    }
    .fr.ent2": file name too long

【问题讨论】:

    标签: python-3.x tkinter tcl


    【解决方案1】:

    在 Tcl 中,exec 运行由具有给定名称的可执行文件定义的子进程(由于其中包含空格和换行符等,真的对于文件名来说是不寻常的,给你一条错误消息,因为你没有这样的可执行文件)。您可能想改用eval

    root.tk.call('eval', code)
    

    【讨论】:

    • FWIW,我真的很喜欢 call 不会为你分词。即使在这种情况下您需要使用eval,它也使在语言之间传输任意数据变得可靠且容易。这比反过来要好得多,当您猜测如何正确添加引用时,这很容易搞砸并且所有这些都是为了暂时的方便。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 1970-01-01
    • 2013-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多