通过在 Python 中使用过程编程范式,我编写了一个程序,该程序逐行读取文件(例如 File.txt)的输入并打印它。下面是示例:
Script:
import fileinput
for line in fileinput.input(r'D:\File.txt'):
line = line.replace(" ", "")
line = line[0:-1]
print(line)
Result:
注意:例如,如果“File.txt”包含 2 行,第一行为“line1”,第二行为“line2”,则输出为:
line1
line2
我希望通过使用“Tkinter Multiline TextBox”而不是文件(在上面的示例 File.txt 中)通过面向对象编程范式获得相同的结果。
我有下面的代码创建一个多行 Tkinter TextBox:
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。
请帮忙...