【问题标题】:How to read the input(line by line) from a multiline Tkinter Textbox in Python?如何从 Python 中的多行 Tkinter 文本框中读取输入(逐行)?
【发布时间】:2013-07-19 13:04:48
【问题描述】:

通过在 Python 中使用过程编程范式,我编写了一个程序,它逐行读取文件(比如 File.txt)的输入并打印出来。下面是例子:

脚本:

import fileinput
for line in fileinput.input(r'D:\File.txt'):
    line = line.replace(" ", "")
    line = line[0:-1]
    print(line)

结果:

注意:例如“File.txt”包含两行,第一行为'line1',第二行为'line2',则输出为:

line1
line2

我希望通过使用“Tkinter Multiline TextBox”而不是文件(在上面的示例 File.txt 中)通过面向对象的编程范式获得相同的结果。

我有下面的代码来创建一个 MultiLine Tkinter 文本框:

import tkinter as tki # Tkinter -> tkinter in Python3
class App(object):

    def __init__(self):
        self.root = tki.Tk()

    # create a Frame for the Text and Scrollbar
        txt_frm = tki.Frame(self.root, width=200, height=200)
        txt_frm.pack(fill="both", expand=True)

        # ensure a consistent GUI size
        txt_frm.grid_propagate(False)

        # implement stretchability
        txt_frm.grid_rowconfigure(0, weight=1)
        txt_frm.grid_columnconfigure(0, weight=1)

    # create a Text widget
        self.txt = tki.Text(txt_frm, borderwidth=3, relief="sunken")
        self.txt.config(font=("consolas", 12), undo=True, wrap='word')
        self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)

    # create a Scrollbar and associate it with txt
        scrollb = tki.Scrollbar(txt_frm, command=self.txt.yview)
        scrollb.grid(row=0, column=1, sticky='nsew')
        self.txt['yscrollcommand'] = scrollb.set

    def retrieve_input():
        input = self.txt.get("0.0",END)
        print(input)
app = App()
app.root.mainloop()
app.retrieve_input()

现在我的问题是,一旦我运行上面的代码,就会出现“Tkinter Multiline TextBox”,我在 Tkinter TextBox 中输入 4 行:

ABC
XYZ
PQR
QAZ

但我没有得到确切的想法/实现,即如何从 Tkinter TextBox 中逐一读取这些行并将它们用于我的程序中的进一步处理。

我使用的 Python 版本是 3.0.1。 请帮忙...

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    从文档中,tkinter.text 上的 get 方法将只返回字符串,包括新行 \n。不能把tkinter.text当作文件,但可以用其他方式。

    1. 阅读它们并将它们分成一个列表。然后循环列表。

      def retrieve_input():
          text = self.txt.get('1.0', END).splitlines()
          for line in text:
              ...
      
    2. 使用io.StringIO 模拟文件,但在这种情况下它不会去除换行符。

      def retrieve_input():
          text = io.StringIO(self.txt.get('1.0', END))
          for line in text:
              line = line.rstrip()
              ...
      

    【讨论】:

    • Text.get('0.0') 只返回第一个字符。
    • 你确定吗?该文档告诉我,如果省略第二个参数,它将在第一个参数之后返回字符。我会试试看。@falsetru
    • infohost.nmt.edu/tcc/help/pubs/tkinter/web/text-methods.html。你可以看看。这是来自官方文档的来源。@falsetru
    • 根据您提供的文档:检索从索引 index1 开始。如果省略第二个参数,则会在 index1 之后获得 character。 (不是字符)
    • 另一个问题:文本小部件的行号从 1 开始,而列号从 0 开始。
    【解决方案2】:

    我修改了你的代码。

    • 添加了一个按钮,点击时将调用retrieve_input
    • retrieve_input 应该有self 参数。

    您可以使用self.txt.get("1.0", tki.END) 获取文本。使用str.splitlines() 获取行作为列表。

    import tkinter as tki
    
    class App(object):
    
        def __init__(self):
            self.root = tki.Tk()
    
        # create a Frame for the Text and Scrollbar
            txt_frm = tki.Frame(self.root, width=200, height=200)
            txt_frm.pack(fill="both", expand=True)
    
            # ensure a consistent GUI size
            txt_frm.grid_propagate(False)
    
            # implement stretchability
            txt_frm.grid_rowconfigure(0, weight=1)
            txt_frm.grid_columnconfigure(0, weight=1)
    
        # create a Text widget
            self.txt = tki.Text(txt_frm, borderwidth=3, relief="sunken")
            self.txt.config(font=("consolas", 12), undo=True, wrap='word')
            self.txt.grid(row=0, column=0, sticky="nsew", padx=2, pady=2)
    
        # create a Scrollbar and associate it with txt
            scrollb = tki.Scrollbar(txt_frm, command=self.txt.yview)
            scrollb.grid(row=0, column=1, sticky='nsew')
            self.txt['yscrollcommand'] = scrollb.set
    
            tki.Button(txt_frm, text='Retrieve input', command=self.retrieve_input).grid(row=1, column=0)
    
        def retrieve_input(self):
            lines = self.txt.get("1.0", tki.END).splitlines()
            print(lines)
    
    app = App()
    app.root.mainloop()
    

    【讨论】:

    • 感谢您提供代码片段。它帮助我为我的问题找到了一个想法。如果我被困在我正在解决的问题之间,我会问你更多。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 1970-01-01
    • 2015-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多