2016-11-18 29 views
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。

回答

0

您只需從文本範圍中刪除「只讀」標籤即可。您需要保存到文本組件的引用:

class Example(Frame): 
    def __init__(self, parent): 
     ... 
     self.text = ReadonlyText(...) 

    def keyrelease(self,event): 
     if some_condition: 
      # make line 5 not readonly 
      self.text.tag_remove("readonly", "5.0", "5.0 lineend") 

注:此代碼是錯誤的:

pos = int(float(index)) 

文本指數浮點數,它們是兩個整數相隔一段時間。如果您將它們視爲浮點數並嘗試對其進行比較,則會得到意想不到的結果。例如,由於浮點數5.2大於5.10,但文本索引5.10之後的5.2

+0

感謝您的回覆和附加評論,這是tkinter的新內容。我試過tag_remove,我可以刪除行中的文本,但不能插入新的文本。所以我進一步嘗試了tag_delete,然後瞧,我可以刪除和插入。但這裏唯一的缺點是所有的線都被激活。 – user3600037

+0

要插入,您必須確保您插入的索引沒有該標籤。該算法非常簡單:如果您嘗試插入或刪除文本,並且您提供的索引位於具有隻讀標記的範圍內,則不允許。 –