2
我已經通過溶液看了一個類似的問題在這裏製作的unedittable線的Tkinter
How can you mark a portion of a text widget as readonly?
,但我曾試圖彌補了一點活力。情況是,標記爲'readonly'
的行可以稍後在程序中根據少量條件進行更改。 這是我的代碼在下面,它叫布賴恩奧克利寫的READONLY
類。
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
global text
text = ReadonlyText(self)
sb = Scrollbar(self, orient="vertical", command=text.yview)
text.configure(state=DISABLED)
text.configure(yscrollcommand=sb.set)
sb.pack(side="left", fill="y")
text.pack(side="right", fill="both", expand=True)
count = 1.0
with open('chem_data2.txt') as f:
for line in f:
if count == 5.0:
text.insert(str(count), line,'readonly')
else:
text.insert(str(count), line, 'readonly')
count = count + 1.0
f.close()
text.bind('<Key>', self.keyrelease)
pos = text.index('end')
text.tag_configure("readonly", foreground="grey")
def keyrelease(self,event):
text.configure(state=NORMAL)
index = text.index(INSERT)
pos = int(float(index))
let = str(float(pos))
word = text.get(str(float(pos)), str(pos) + '.end')
print pos
#pos = text.index('end')
if float(pos) == 5.0:
print 'i got here'
#text.insert(str(5.0), 'line', 'read')
上面的代碼需要一個文件作爲輸入,並標記該文件'readonly'
的每一行的初始階段,但如果用戶光標在第五行的行應該改變到edittable。
感謝您的回覆和附加評論,這是tkinter的新內容。我試過tag_remove,我可以刪除行中的文本,但不能插入新的文本。所以我進一步嘗試了tag_delete,然後瞧,我可以刪除和插入。但這裏唯一的缺點是所有的線都被激活。 – user3600037
要插入,您必須確保您插入的索引沒有該標籤。該算法非常簡單:如果您嘗試插入或刪除文本,並且您提供的索引位於具有隻讀標記的範圍內,則不允許。 –