[英]How to remove a Warning label from Tkinter GUI
我有一些代碼想要檢查用戶對兩個 tk 條目的輸入的有效性,如果輸入的是字母而不是數字,它會以紅色文本發布警告 - 這是正確執行的。 我希望它做的是在用戶插入數字后刪除紅色文本 - 目前紅色 ValueError 文本仍然存在,如果兩個條目是數字,我希望它在按下按鈕后消失。
代碼
print('\n'*3)
import tkinter as tk
root = tk.Tk()
pw_low = 0.01
pw_high = 30.0
lab1 = tk.Label(root, text="Pulse Width Start (\u03bcS):").grid(row = 0)
start_pw = tk.StringVar()
entry1 = tk.Entry(root, width=20, textvariable = start_pw).grid(row = 0, column = 1)
start_pw.set(pw_low)
lab2 = tk.Label(root, text="Pulse Width End (\u03bcS):").grid(row = 1)
end_pw = tk.StringVar()
entry2 = tk.Entry(root, width=20, textvariable = end_pw).grid(row = 1, column = 1)
end_pw.set(pw_high)
def getPWrange():
try:
user_start_pw_num = float(start_pw.get())
except ValueError:
answer_label.config(text = 'You must enter an integer or decimal number', fg = 'red')
try:
user_end_pw_num = float(end_pw.get())
user_pw_range = [user_start_pw_num, user_end_pw_num ]
print('user_pw_range: ',user_pw_range)
except ValueError:
answer_label.config(text = 'You must enter an integer or decimal number', fg = 'red')
button = tk.Button(root, text="Range", command = getPWrange)
button.grid(row = 2, column = 3)
answer_label = tk.Label(root, text = '')
answer_label.grid(row = 3)
root.mainloop()
不滿意的解決方案
添加一個標簽銷毀使用 after 確實會在添加一個數字后刪除標簽但是如果在此之后輸入了一個字母,警告錯誤不會顯示,而是我得到一個回溯
def getPWrange():
try:
user_start_pw_num = float(start_pw.get())
except ValueError:
answer_label.config(text = 'You must enter an integer or decimal number', fg = 'red')
answer_label.after(2000, answer_label.destroy)
try:
user_end_pw_num = float(end_pw.get())
user_pw_range = [user_start_pw_num, user_end_pw_num ]
print('user_pw_range: ',user_pw_range)
except ValueError:
answer_label.config(text = 'You must enter an integer or decimal number', fg = 'red')
Traceback (most recent call last):
File "/Users/.../opt/anaconda3/lib/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "/Users/.../Desktop/tk_gui_grid/t6.py", line 24, in getPWrange
answer_label.config(text = 'You must enter an integer or decimal number', fg = 'red')
File "/Users/.../opt/anaconda3/lib/python3.7/tkinter/__init__.py", line 1485, in configure
return self._configure('configure', cnf, kw)
File "/Users/.../opt/anaconda3/lib/python3.7/tkinter/__init__.py", line 1476, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".!label3"
期望輸出
如果所有條目都有效,則將刪除 answer_label 。
刪除try
塊中標簽的文本就足夠了:
try:
user_start_pw_num = float(start_pw.get())
user_end_pw_num = float(end_pw.get())
user_pw_range = [user_start_pw_num, user_end_pw_num ]
print('user_pw_range: ',user_pw_range)
answer_label.config(text='')
except ValueError:
answer_label.config(text='You must enter an integer or decimal number', fg='red')
將兩個try
- except
塊合並為一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.