Python:Tkinter:多行滚动输入框

时间:2015-05-04 07:14:35

标签: python tkinter

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

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

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

但它似乎没有用,一个窗口里面没有任何内容。 你能帮帮我吗?

#########编辑

新代码:

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

很抱歉,如果它看起来像一些失败的选民没有努力(即使我花了一天多的时间),但多行文字输入并不完全是我们可以称之为记录,以便自己学习。

2 个答案:

答案 0 :(得分:1)

您的第一个问题是您注释了app = EntryDemo( rootWin )来电,因此除了创建Tk()根窗口,然后开始其主循环之外,您实际上并没有做任何事情。

如果您解决了这个问题,那么您的下一个问题就是您尝试使用ScrolledText模块,就像它是一个类一样。您需要ScrolledText.ScrolledText类。

如果您解决了这个问题,那么您的下一个问题就是您要从空文本字段尝试delete,这会引发某种Tcl索引错误,然后您就会出现问题还试图在空文本字段中的位置0处insert,这将引发相同的错误。没有理由完全使用delete,而对于insert,您可能希望使用INSERT作为职位。

之后你还有很多问题,但修好这三个问题会使编辑框显示出来,以便你可以开始调试其他所有问题。

答案 1 :(得分:0)

基于您的代码的工作示例。请注意上面的注释,您导入的文件和文件中的类都被命名为“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()