Tkinter 文本小部件 - 为什么 INSERT 不能用作文本​​索引?

Tkinter text widget - Why does INSERT not work as text index?

我有一个困扰我的问题。我目前正在构建一个带有 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 工作,这让我非常沮丧,因为我在我的每个示例代码中都看到了它跨越

INSERT无法直接使用

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

from tkinter import * # this is not a good practice

INSERTCURRENTENDtkinter.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的答案也可以。

使用 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() 

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

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