【问题标题】:Tkinter text widget - Why does INSERT not work as text index?Tkinter 文本小部件 - 为什么 INSERT 不能用作文本​​索引?
【发布时间】:2020-07-10 15:38:19
【问题描述】:

我有一个困扰我的问题。我目前正在使用 Tkinter GUI 构建一个小应用程序。

在首页,我想要一些介绍性文字,无论是文本还是滚动文本小部件。我遇到的代码示例使用 INSERT、CURRENT 和 END 等关键字在小部件内进行索引。

我已经将以下代码复制粘贴到我的编辑器中,但它无法识别 INSERT(抛出错误:“NameError: name 'INSERT' is not defined”):

import tkinter as tk
from tkinter import scrolledtext

window = tk.Tk()
window.title("test of scrolledtext and INSERT method")
window.geometry('350x200')

txt = scrolledtext.ScrolledText(window,width=40,height=10)
txt.insert(INSERT,'You text goes here')
txt.grid(column=0,row=0)

window.mainloop()

如果我将 [INSERT] 更改为 [1.0],我可以让代码工作,但我无法让 INSERT 工作非常令人沮丧,因为我在我遇到的每个示例代码中都看到了它

【问题讨论】:

    标签: python python-3.x tkinter tkinter-text


    【解决方案1】:

    您不需要使用 tkinter 常量。我个人认为最好使用原始字符串“insert”、“end”等。它们更灵活。

    但是,常量对您不起作用的原因是您没有直接导入它们。你导入tkinter的方式,需要使用tk.INSERT等。

    【讨论】:

    • 非常感谢。实际上,我通过弄乱足够长的时间来发现原始字符串。我有一种潜在的挫败感。我花了很多时间搜索 - 并最终找到这样的东西 - 我缺乏一个适当而简洁的参考手册,其中包含清晰和更新的语法。你们更有经验的人使用什么语法参考(例如,查找时,INSERT 是一个 tkinter.constant,但您可以使用“insert”代替)?
    • @AndersF.:tkinter 只是 tcl/tk 的包装器。这在the official python documentation for tkinter 的第二段中进行了描述。每个小部件和每个选项的规范、详尽的文档可以在tcl/tk man pages 中找到
    【解决方案2】:

    INSERT不能直接使用。

    您过去可以使用它,只是因为您过去使用过它:

    from tkinter import * # this is not a good practice
    

    INSERT,CURRENTENDtkinter.constants。现在在你的代码中,你甚至没有导入它们。

    如果你想使用它们,你可以使用

    from tkinter.constants import * # not recommended
    
    ...
    txt.insert(INSERT,'You text goes here')
    

    或者

    from tkinter import constants
    
    ...
    txt.insert(constants.INSERT,'You text goes here') # recommend
    

    如果不想导入,也可以使用:

    txt.insert("insert",'You text goes here')
    

    编辑:我在tkinter的源代码中找到,它已经导入它们,reboot的答案也可以。

    【讨论】:

      【解决方案3】:

      使用tk.INSERT 而不仅仅是INSERT。显示完整代码。

      import tkinter as tk
      from tkinter import scrolledtext
      
      window = tk.Tk()
      window.title("test of scrolledtext and INSERT method")
      window.geometry('350x200')
      
      txt = scrolledtext.ScrolledText(window,width=40,height=10)
      txt.insert(tk.INSERT,'You text goes here')
      txt.grid(column=0,row=0)
      
      window.mainloop() 
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-12-16
        • 2020-07-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多