作為對此的后續問題:

uj5u.com熱心網友回復:
對于你問題的第二部分
由于wrap設定,出現路徑不完整的問題。要解決這個問題,只需更改此字串:
mypathtext = Text(mylabelframe, width=10, height=1)
具有反斜杠和正斜杠的功能,您可以使用.replace()方法修復。
uj5u.com熱心網友回復:
這個怎么樣:
from tkinter import *
from tkinter import filedialog
from tkinter import scrolledtext
import os
def browsefunc():
global content
filename = filedialog.askopenfilename()
infile = open(filename, 'r')
content = infile.read()
pathadd = filename
pathtext.delete(0.0, END)
pathtext.insert(0.0, pathadd)
contenttext.delete(0.0, END)
contenttext.insert(0.0, content)
w = Tk()
w.geometry('600x370')
lb1 = Label(text="Select text file")
lb1.place(x=0, y=0)
bt1 = Button(text="Process", command=browsefunc)
bt1.place(x=0, y=40)
pathtext = Text()
pathtext.place(x=0, y=85, width=450, height=20)
contenttext = scrolledtext.ScrolledText()
contenttext.place(x=0, y=120, width=450)
讀取檔案后,您的資料將在content變數中。
uj5u.com熱心網友回復:
查看除錯器后,發現 TextIO 變數“fork”包含兩部分:“<_io.Textwrapper”和“name = C:\blah\blah\blah”

我得到了 99% 的作業是這樣的:
#import os
#import io
from tkinter import *
#from tkinter import ttk
from tkinter import filedialog
from tkinter import scrolledtext
import tkinter as tk
from pathlib import Path
from typing import TextIO
def forkscroll():
mylabelframe = tk.LabelFrame(myframe, text='My Long Text:').pack()
scroll_w = 30
scroll_h = 10
myscrolledtext = scrolledtext.ScrolledText(mylabelframe, width=scroll_w, height=scroll_h, wrap=tk.WORD)
myscrolledtext.vbar.config(width=20)
myscrolledtext.grid(sticky='news', row=6, column=0, rowspan=1, columnspan=1, padx=5, pady=5)
# Open a dialogue; select and load a text file; read the text file directly into the scrolledtext widget (box)
fork: TextIO = open(filedialog.askopenfilename(), 'r')
myscrolledtext.insert(tk.END, fork.read()) ### This reads the content of "fork" into the scrolledtext widget
forkname = fork.name # works
mypathtext = Text(mylabelframe, width=10, height=1, wrap=tk.WORD)
mypathtext.grid(sticky='news', row=5, column=0, rowspan=1, columnspan=1, padx=5, pady=5)
mypathtext.insert(tk.END, forkname) # works
#GUI
root = Tk()
root.title('Root Title')
root.geometry('600x300')
myframe = tk.Frame(root, width=300, height=300)
myframe.winfo_toplevel().title('MyFrame Title')
myframe.grid(column=0, row=0, sticky='news')
myforkpath = StringVar()
f1 = Frame(myframe, width=900, height=150) #file1
f1.pack(fill=X, side =TOP)
f2 = Frame(myframe, width=900, height=150) #file2
f2.pack(fill=X, side=BOTTOM)
Label(f1, text="Select text file").grid(row=0, column=0, sticky='e') # select file button label
run_button = Button(myframe, text="Process", command=forkscroll).pack()
Label(f2, text="put the content of the file in the text scroll box below").grid(row=1, column=0, sticky='s')
myframe.mainloop()
...有一個問題...那 1%
我的筆記本電腦被命名為“Crappy Laptop”(不是真的,但它在路徑的那部分名稱中有一個空格),因此列印到文本小部件欄位的名稱路徑是:
“C://用戶/糟糕”
...我沒有完整的路徑...應該是“C://Users/Crappy Laptop/Desktop/My/Python/Code/mylongtextfile.txt”
事實上,我得到的是正斜杠,而不是反斜杠......在 Pycharm 控制臺視窗中,它顯示了每個方向都有斜杠的路徑!像這樣: C:\......\python.exe C://.../.../myfile.py
如何處理空間?
好吧,到目前為止我已經做到了...
forkname = fork.name # works
# fix the "path with spaces problem"
newforkname1 = forkname.replace(' ', '_')
print(newforkname1)
newforkname2 = newforkname1.replace('/', '\\')
print(newforkname2)
mypathtext = Text(mylabelframe, width=10, height=1, wrap=tk.WORD)
mypathtext.grid(sticky='news', row=5, column=0, rowspan=1, columnspan=1, padx=5, pady=5)
#mypathtext.insert(tk.END, forkname) # works
mypathtext.insert(tk.END, newforkname2) # works
還沒有弄清楚如何顯示空格而不是下劃線。
這完全不行……
newforkname1 = forkname.replace(' ', ' '.join(forkname))
uj5u.com熱心網友回復:
這是一個單獨的答案,因為我從上一個問題和這個問題中解決了一個問題,但創造了一個新問題:D
我能夠使用 StringVar 將文本檔案中的字串內容從一個函式傳遞到另一個函式......
所以我在代碼頂部添加了新的 StringVars
reflines_sv = StringVar()
cfglines_sv = StringVar()
然后在一個函式中,我打開文本檔案,獲取內容,并將其傳遞給一個字串,然后傳遞給一個字串變數:
def getref():
# COMMENT: Get reference file
Label(frame_input, anchor='w', width=80, text='Reference filepath:', background='#abdbe3').pack(side=TOP, fill=Y)
ref: TextIO = open(filedialog.askopenfilename(title='add Reference file', initialdir='src', ), 'r')
reflines = ref.readlines()
reflines_sv.set(reflines)
# COMMENT: Get reference file path
refname = ref.name
refname_new = refname.replace('/', '\\')
pathtext_ref = Text(frame_input, width=80, height=1, bg='#f0f0f0')
pathtext_ref.pack(anchor='n', side=TOP, fill=Y, ipadx=5, ipady=5)
pathtext_ref.configure(font=("Arial", 9, "italic",))
pathtext_ref.insert(tk.END, refname_new)
return reflines_sv
然后在下一個函式中,我可以檢索內容并使用它。
def process():
try:
# COMMENT: Reset output
rdiff.set('')
tdiff.set('')
rtmiss.set('')
reflines = reflines_sv.get()
cfglines = cfglines_sv.get()
# COMMENT: Comparing lines
refhash = dict()
cfghash = dict()
different = False
etc...
這樣做的好處是我現在可以擁有一個帶有單獨按鈕的向導,用于處理文本檔案的不同階段。
可能有更好的方法可以做到這一點,但我還沒有找到。
新的問題是,現在文本檔案的內容沒有正確輸出。
等等... =下面的代碼
for i, value in enumerate(reflines):
refhash[i] = value
for i, value in enumerate(cfglines):
cfghash[i] = value
contains = value in refhash.values()
different = different or not contains
if not contains:
tdiff.set(tdiff.get() 'problem line ' str(i) ': ' value) ### <- new problem!
for i, value in enumerate(reflines):
contains = value in cfghash.values()
different = different or not contains
if not contains:
rdiff.set(rdiff.get() 'line ' str(i) ': ' value)
if not different:
errmsg.set('no differences')
if len(reflines) == len(cfglines) and different:
for i, _ in enumerate(reflines):
if cfglines[i] != reflines[i]:
rtmiss.set(rtmiss.get() 'line ' str(i) '\n')
else:
rtmiss.set('files have different number of lines')
scroll_w = 15
scroll_h = 5
myscrolledtext1 = scrolledtext.ScrolledText(frame_input, width=scroll_w, height=scroll_h, wrap=tk.WORD,background='#bbffe6')
myscrolledtext1.vbar.config(width=20)
myscrolledtext1.pack(anchor='s', fill=X, side=LEFT, ipadx=5,ipady=5, expand=True)
myscrolledtext1.insert(tk.END, rdiff.get())
myscrolledtext2 = scrolledtext.ScrolledText(frame_input, width=scroll_w, height=scroll_h, wrap=tk.WORD, background='#bbffe6')
myscrolledtext2.vbar.config(width=20)
myscrolledtext2.pack(anchor='s', fill=X, side=LEFT, ipadx=5,ipady=5, expand=True)
myscrolledtext2.insert(tk.END, tdiff.get())
myscrolledtext3 = scrolledtext.ScrolledText(frame_input, width=scroll_w, height=scroll_h, wrap=tk.WORD,background='#bbffe6')
myscrolledtext3.vbar.config(width=20)
myscrolledtext3.pack(anchor='s', fill=X, side=LEFT, ipadx=5,ipady=5, expand=True)
myscrolledtext3.insert(tk.END, rtmiss.get())
except OSError:
errmsg.set('failed to load both files')
# COMMENT: Buttons
button_ref = Button(frame_button, text="Browse for ref file", font='50', command=getref).pack(anchor='s', side=BOTTOM, pady=10, ipadx=5, ipady=20)
button_cfg = Button(frame_button, text="Browse for test file", font='50', command=getcfg).pack(anchor='s', side=BOTTOM, pady=10, ipadx=5, ipady=20)
button_process = Button(frame_button, text="Process", font='50', command=process).pack(anchor='s', side=BOTTOM, pady=10, ipadx=5, ipady=20)
以前沒有這樣做過,當我通過一個按鈕將所有功能集中在一個功能中時。
查看除錯器,我看到每個函式中的字串發生了什么。
# cfglines in get getcfg() prints ['BING\n,'BONG\n', etc..
# cfglines in process() prints as (\'BING\\n\',\'BONG\\n\', etc...
所以我需要洗掉并替換底線以使其看起來像頂線,然后一切正常。
問題是,使用 readlines() 創建的原始變數是一個字串陣列,當它被傳遞給 stringvar 時,它變成了一個元組,再次將它帶入另一個函式意味著它可以變成一個無用的字串,或一個元組,您可以將其轉換為所有分隔字符的無用陣列,因為如果您不知道檔案的內容是什么,則無法將其拆分為陣列。
因此,將文本檔案的內容從一個函式傳遞到另一個函式的程序需要更好的解決方案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/505343.html
