【问题标题】:Read one line at a time from tkinter textbox从 tkinter 文本框中一次读取一行
【发布时间】:2019-09-20 17:52:55
【问题描述】:

我可以从输入框中一次读取一行,并将其显示在新框中,但我需要前进到下一行代码。

这是 GUI 中的文本框

    self.sourcecode = Text(master, height=8, width=30)
    self.sourcecode.grid(row=1, column=1, sticky=W)

    self.nextline = Button(master, text="Next Line", fg="orange", command=lambda:[self.nextLine(self.intcount), self.lexicalResult()])
    self.nextline.grid(row=12, column=1, sticky=E)

    self.lexicalresult = Text(master, height=8, width=30)
    self.lexicalresult.grid(row=1, column=3, sticky=W)

这些是我从一个盒子复制到另一个盒子的函数(输出将 insert()lexicalResult() 函数中)

def nextLine (self, intcount):
    print("Reading from source")
    self.linenumber.delete('1.0', END)
    self.intcount = self.intcount + 1
    self.linenumber.insert('0.0', self.intcount)
    self.retrieve_input()

def retrieve_input(self):
    lines = self.sourcecode.get('1.0', '2.0') #I need to take this and move to the next line but i am new to python and don't know what functions there are or their arguments
    self.lexicalresult.insert('1.0', lines)

def lexicalResult (self):
    print("Printing to result")

【问题讨论】:

  • 运行该代码时会发生什么?它有什么作用,它与您的预期有何不同?
  • @BryanOakley 如果我在源代码框中输入两行源代码,它会在结果框的同一行输出两行,中间只有一个空格。我希望它读取一行,然后打印一行,然后重复
  • 使用explain-tkinter-text-search-method 或获取整个sourcecode 并执行split('\n')
  • Split 非常感谢!

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


【解决方案1】:

您可以通过在索引上使用“lineend”修饰符来读取单行文本。例如,要获取所有第 1 行,您可以使用如下内容:

text.get("1.0", "1.0 lineend")

这将得到所有的行除了尾随的换行符。如果您想要尾随换行符,请多获取一个字符:

text.get("1.0", "1.0 lineend+1c")

要删除整行,您可以使用完全相同的索引并将它们传递给delete 方法。

作为更通用的规则,给定任何索引,要计算下一行的开头,您可以使用以下内容:

next_line = text.index("{} lineend+1c".format(index))

index 方法将索引转换为其规范形式。 "lineend" 修饰符将索引更改为行尾,+1c 将其移动一个字符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-21
    • 2021-05-08
    • 1970-01-01
    • 2014-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多