I would like to display a warning if the user does not input integers into an Entry
, here is a minimal example:
import tkinter as tk
from tkinter import messagebox
class MainWindow(tk.Tk):
""" The main window
"""
def __init__(self):
tk.Tk.__init__(self)
self.configure_window()
def configure_window(self):
""" Configure the main window
"""
self.geometry("600x400")
self.title("Testing entry validate command")
self.bind_all('<Control-w>', lambda e: self.destroy())
var1 = tk.StringVar(value="0")
vcmd = (self.register(self.validate_input))
entry1 = tk.Entry(
self,
textvariable=var1,
validate='all',
validatecommand=(vcmd, '%P'))
entry1.place(relx=0.5, rely=0.5, anchor=tk.CENTER)
def validate_input(self, txt):
""" Validate that the input only contains digits
"""
print(txt)
if str.isdigit(txt) or txt == "":
return True
messagebox.showwarning(
"Alert", "Please enter a positive integer")
return False
def main():
window = MainWindow()
window.mainloop()
main()
The problem is that the validate_input()
method is not called after the warning message has been shown a first time. For example if the user enter "0", "1", "r" (three key strokes) into the entry, validate_input()
is called for each key stroke, and for the last key stroke (the letter "r") the warning message box is shown. Next, if the user continues to type (after pressing "OK" in the warning message box) into the Entry, the validate_input()
method is not called any more for the following key strokes. Expected behaviour would be that it is called for any key stroke independent of whether the message box has been shown or not.
What can be the problem?