I'm usign Python 3.x with Tkinter; I would like to check that the value of a tkinter.Entry is a number by calling a function called "is_valid_entry" and passing all args via validatecommand. I would like to use the same function for other entries too. The problem is that inside is_valid_entry I can't clean the entry text with self.delete(0,END) because self is seen as str instead of tkinter.Entry. I hope I made it understandable, thanks for the help!
Here's the code :
from tkinter import *
from tkinter import ttk
from tkinter import filedialog as fd
import tkinter as tk
window = tk.Tk()
window.geometry("600x600")
window.title("Hello Stackoverflow")
window.resizable(False,False)
def isfloat(value):
try:
float(value)
return True
except ValueError:
return False
def is_valid_entry(self,value):
if (value.isnumeric() or isfloat(value)):
return True
else:
tk.messagebox.showerror(title="Error!", message="Value must be a number!")
print(type(self))
self.delete(0,END) # I'd like to clean the entry text but self is type string now not type tkinter.Entry
return False
e2=tk.Entry(window,width=20)
e2.grid(row=6,column=2,padx=5)
print(type(e2))
okayCommand = e2.register(is_valid_entry)
e2.config(validate='focusout',validatecommand=(okayCommand,e2,'%P'))
if __name__ == "__main__":
window.mainloop()
I tried to use a function to check if an entry text is a valid number. I registered the function and configured the entry to call this function in case of 'focusout' via validatecommand. I would like to pass the entry as well (self) as args of validatecommand so that when the function is executed , in case of invalid number, the text in the entry is cleared. The entry param inside the function is seen as a str instead of a tkinter.Entry.
CodePudding user response:
A workaround is to store the widgets in a dictionary with a string key and pass that key in the config
setting.
def is_valid_entry(value, widgetname):
if (value.isnumeric() or isfloat(value)):
return True
else:
tk.messagebox.showerror(title="Error!", message="Value must be a number!")
mywidgets[widgetname].delete(0,END)
return False
e2=tk.Entry(window,width=20)
e2.grid(row=6,column=2,padx=5)
mywidgets = dict()
mywidgets["e2"] = e2
print(type(e2))
okayCommand = e2.register(is_valid_entry)
e2.config(validate='focusout',validatecommand=(okayCommand,'%P','e2'))
CodePudding user response:
The problem is that inside is_valid_entry I can't clean the entry text with self.delete(0,END)
self.delete(0,END)
to:
e2.delete(0,END)