【发布时间】:2021-01-13 18:07:30
【问题描述】:
我有一些代码想要检查用户输入到两个 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。
【问题讨论】:
标签: python user-interface tkinter label try-catch