2016-12-06 56 views
0

我正在嘗試使用16個字符的限制進行輸入。 到目前爲止,我有這樣的事情:Tkinter - validatecommand +退格

import tkinter as tk 

rt = tk.Tk() 

def tr_input(): 
    a = e['textbox'] 
    b = a.get() 
    print(b) 
    if "\b" in b: 
     return True 
    if "\n" in b: 
     calculate() 
    elif len(b)>16: 
     return False 
    return True 

e = { "textbox":tk.Entry(rt,validate = "all",validatecommand=tr_input) } 

calculate()對在條目數量計算,並將其顯示在另一個標籤

它工作正常,並阻止任何進一步的字符後從被輸入第16個。但是,它也可以防止通過退格刪除字符,我不知道如何......沒有這樣做。
有誰知道我該如何解決這個問題?

編輯:具體來說,我需要能夠找出是否最後一次按下按鈕是退格

回答

0

你可以有validatecommand通信息,這樣你就不必檢測任何按鍵。例如,如果允許進行編輯,您可以告訴它傳遞小部件中的值。您可以根據所需的長度檢查該值,而無需知道用戶是添加還是刪除字符,或者是鍵入字符還是將其粘貼。

您可以通過首先註冊命令以及參數傳遞給你的命令。例如:最後

e = { "textbox":tk.Entry(rt,validate = "all",validatecommand=vcmd) } 

,修改tr_input函數接受這些參數:

vcmd = (rt.register(tr_input), '%d', '%P', '%s') 

然後,您可以通過這個vcmdvalidatecommand選項

def tr_input(d, P, s): 
    # d = type of action (1=insert, 0=delete, -1 all others) 
    # P = value of entry if edit is allowed 
    # s = value of entry prior to allowing the edit 
    print("tr_input: d='%s' P='%s' s='%s'" % (d,P,s)) 
    if len(P) > 16: 
     return False 
    return True 

欲瞭解更多信息,請參閱本回答:https://stackoverflow.com/a/4140988/7432