Python: Tkinter: 多行滚动输入框

Python: Tkinter: Multi line scrolling entry box

我想让 Tkinter window 能够请求多行输入 (因此用户将添加一行或多行文本) 然后当我们点击按钮时能够检索用户输入的值以供进一步使用。

到目前为止我有这个脚本:

from Tkinter import *
import ScrolledText

class EntryDemo:
  def __init__(self, rootWin):
    #Create a entry and button to put in the root window
    self.textfield = ScrolledText(rootWin)
    #Add some text:
    self.textfield.delete(0,END)
    self.textfield.insert(0, "Change this text!")
    self.textfield.pack()

    self.button = Button(rootWin, text="Click Me!", command=self.clicked)
    self.button.pack()



  def clicked(self):
    print("Button was clicked!")
    eText = self.textfield.get()
    print("The Entry has the following text in it:", eText)


#Create the main root window, instantiate the object, and run the main loop
rootWin = Tk()
#app = EntryDemo( rootWin )
rootWin.mainloop()

但是好像没有用,A window 空空如也的出现了。 你能帮帮我吗?

#########编辑

新代码:

from Tkinter import *
import ScrolledText

class EntryDemo:
  def __init__(self, rootWin):

    self.textfield = ScrolledText.ScrolledText(rootWin)
    #Add some text:
    #self.textfield.delete(0,END)
    self.textfield.insert(INSERT, "Change this text!")
    self.textfield.pack()

    self.button = Button(rootWin, text="Click Me!", command=self.clicked)
    self.button.pack()



  def clicked(self):
    eText = self.textfield.get(1.0, END)
    print(eText)

rootWin = Tk()
app = EntryDemo( rootWin )
rootWin.mainloop()

抱歉,如果它看起来像是一些反对者毫不费力地完成的(即使我花了一天多的时间在上面),但多行文本输入并不完全是我们可以称之为有据可查的,可以自己学习的。

您的第一个问题是您注释掉了 app = EntryDemo( rootWin ) 调用,因此您实际上并没有做任何事情,只是创建了一个 Tk() 根目录 window,然后开始其主循环。

如果你解决了这个问题,你的下一个问题是你试图像使用 class 一样使用 ScrolledText 模块。你需要 ScrolledText.ScrolledText class.

如果你解决了这个问题,你的下一个问题是你试图从一个空的文本字段 delete,这会引发某种 Tcl 索引错误,然后你也在尝试到空文本字段中位置 0 的 insert,这将引发相同的错误。根本没有理由做 delete,对于 insert 你可能想使用 INSERT 作为位置。

在那之后你仍然有多个问题,但是修复这三个问题将会启动并显示你的编辑框,这样你就可以开始调试其他所有内容了。

一个基于您的代码的工作示例。请注意上面的注释,您导入的文件和文件中的 class 都被命名为 "ScrolledText"

from Tkinter import *
import ScrolledText

class EntryDemo:
    def __init__(self, rootWin):
        #Create a entry and button to put in the root window
        self.textfield = ScrolledText.ScrolledText(rootWin)
        self.textfield.pack()
        #Add some text:
        self.textfield.delete('1.0', END)
        self.textfield.insert('insert', "Change this text!")

        self.button = Button(rootWin, text="Click Me!",
                             command=self.clicked)
        self.button.pack()



    def clicked(self):
        print("Button was clicked!")
        eText = self.textfield.get('1.0', END)
        print("The Entry has the following text in it:", eText)
        self.textfield.delete('1.0', END)


rootWin = Tk()
app = EntryDemo( rootWin )
rootWin.mainloop()