當兩個密碼不匹配時,如何禁用 tkinter 視窗中的按鈕?
我的作業:
from tkinter import *
from functools import partial
root = Tk()
root.geometry('280x100')
root.title('Tkinter Password')
def validation_pw(ep,cp):
if ep.get() == cp.get():
Label(root, text = "Confirmed").grid(column=0, row=5)
else:
Label(root, text = "Not matched").grid(column=0, row=5)
# check_button['state'] = DISABLED <============================
ep = StringVar()
cp = StringVar()
Label1 = Label(root, text = "Enter Password").grid(column=0, row=0)
pwEnty = Entry(root, textvariable = ep, show = '*').grid(column=1, row=0)
# Confirmed password label
Label2 = Label(root, text = "Confirm Password").grid(column=0, row=1)
pwconfEnty = Entry(root, textvariable = cp, show = '*').grid(column=1, row=1)
validation_pw = partial(validation_pw, ep,cp)
check_button = Button(root, text = "check", command = validation_pw).grid(column=0, row=4)
root.mainloop()
它顯示兩個密碼是否不匹配。

現在,如果兩個密碼不匹配,我想禁用復選按鈕。如果失敗,我希望用戶不能再嘗試密碼。
所以在函式validation_pw中,我添加了check_button['state'] = DISABLED.
但是,會彈出一個錯誤
TypeError: 'NoneType' object does not support item assignment
如何解決這個問題?謝謝!
uj5u.com熱心網友回復:
您的檢查按鈕實際上是無,因為它是grid函式的結果。
要修復它,首先宣告按鈕,然后對其進行網格化。
前:
check_button = Button(
root, text = "check",
command = validation_pw).grid(column=0, row=4) # Result of Button.grid function
print(check_button) # None
后:
check_button = Button(root, text = "check", command = validation_pw)
check_button.grid(column=0, row=4)
print(check_button) # Button object ...
uj5u.com熱心網友回復:
你會得到錯誤,NoneType因為在某一時刻它沒有被分配任何東西。這是因為您.grid在與按鈕相同的行上使用了。固定代碼:
from tkinter import *
from functools import partial
root = Tk()
root.geometry('280x100')
root.title('Tkinter Password')
def validation_pw(ep,cp):
if ep.get() == cp.get():
Label(root, text = "Confirmed").grid(column=0, row=5)
else:
Label(root, text = "Not matched").grid(column=0, row=5)
check_button['state'] = DISABLED
ep = StringVar()
cp = StringVar()
Label1 = Label(root, text = "Enter Password").grid(column=0, row=0)
pwEnty = Entry(root, textvariable = ep, show = '*').grid(column=1, row=0)
# Confirmed password label
Label2 = Label(root, text = "Confirm Password").grid(column=0, row=1)
pwconfEnty = Entry(root, textvariable = cp, show = '*').grid(column=1, row=1)
validation_pw = partial(validation_pw, ep,cp)
check_button = Button(root, text = "check", command = validation_pw)
check_button.grid(column=0, row=4)
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/491108.html
