我剛開始Tkinter的一個星期前,我試圖向GUI鏈接寫在的Python自動代碼生成腳本。在這個論壇的幫助下,我幾乎涵蓋了所有的案例,但是這個特別的案例讓我難以置信。Tkinter的 - 當兩個輸入小寫入觸發一個事件,無論爲了
我需要2個輸入小部件,並且一旦輸入它們就計算它們之間的關係(即沒有按鈕小部件來觸發一個功能)。我意識到必須完成事件,所以經過一番嘗試,我已經提出了以下這些工作,但感覺就像我不是'pythonic'一樣。
from Tkinter import *
root = Tk()
root.title("Test")
def OnValidate(S):
if S.isdigit():
return True
else:
return False
def insert_text_widg(widg,msg):
widg.delete(1.0,END)
widg.insert(INSERT,msg)
# Checks the required conditions
def check_var1(event):
try:
temp1=int(var1_ent.get())
temp2=int(var2_ent.get())
except ValueError:
return
if(temp2 > temp1):
insert_text_widg(log_text,"ERROR: Var2 cannot be greater than Var1")
for ent in [var1_ent,var2_ent]:
ent.configure(bg='indian red',fg='white')
elif ((temp1 - temp2) % 2) == 1:
insert_text_widg(log_text,"ERROR: Difference cannot be odd")
for ent in [var1_ent,var2_ent]:
ent.configure(bg='indian red',fg='white')
else:
log_text.delete(1.0,END)
for ent in [var1_ent,var2_ent]:
ent.configure(bg='white',fg='black')
# Duplicate of check_var1
def check_var2(event):
try:
temp2=int(var2_ent.get())
temp1=int(var1_ent.get())
except ValueError:
return
if(temp2 > temp1):
for ent in [var1_ent,var2_ent]:
ent.configure(bg='indian red',fg='white')
insert_text_widg(log_text,"ERROR: Var2 cannot be greater than Var1")
elif ((temp1 - temp2) % 2) == 1:
for ent in [var1_ent,var2_ent]:
ent.configure(bg='indian red',fg='white')
insert_text_widg(log_text,"ERROR: Difference cannot be odd")
else:
log_text.delete(1.0,END)
for ent in [var1_ent,var2_ent]:
ent.configure(bg='white',fg='black')
# App Configuration
vcmd = (root.register(OnValidate),'%S')
var1_lab = Label(root,text='Var1 :')
var1_lab.pack()
var1_ent = Entry(root,validate="key",validatecommand=vcmd)
var1_ent.bind("<KeyRelease>",check_var1)
var1_ent.pack()
var2_lab = Label(root,text='Var2 :')
var2_lab.pack()
var2_ent = Entry(root,validate="key",validatecommand=vcmd)
var2_ent.bind("<KeyRelease>",check_var2)
var2_ent.pack()
log_text = Text(root)
log_text.pack()
root.mainloop()
有兩個函數(check_var1()& check_var2())基本上做到這一點,我希望合併成一個同樣的事情。 只要任何一個Entry小部件註冊了一個更改,就需要執行檢查。
因此,在短期,我想一個方法調用check_var1()功能,只要任一輸入窗口小部件類型中,不分先後順序的,他們在鍵入。
任何幫助或向正確方向微調將受到高度讚賞。
你爲什麼不使用: var2_ent.bind( 「」,check_var1)??? –
主要問題是用戶輸入輸入的順序。我嘗試了您的建議,但是如果用戶在Var1爲空並返回時首先輸入Var2,則會發生異常。也許我正在處理異常錯誤? – amuneeb