I am working on a big programme and I want Combobox to accept text only to be entered in it
I use This Code
import tkinter
import ttk
import re
win = tkinter.Tk()
def num_only(num):
if str.isdecimal(num):
return True
elif num=="":
return True
else:
return False
def text_only(txt):
if re.match("^\[a-z\]*$",txt.lower()):
return True
elif re.match("^\[أ-ي\]*$",txt):
return True
elif txt == "":
return True
else:
return False
ttk.combobox(win,font="none 12 bold",validate="key",validatecommand(self.text_only,"%P"),values("value1","value2","value3","value4")
win.mainloop()
the validate don't work but it worked with tk.Entry
ttk is a module of tkinter, so you have to import it like this:
from tkinter import ttk
Or instead of calling ttk.Combobox
(note that python is case sensitive, so a call to ttk.combobox
will not work), you can call it like
tkinter.ttk.Combobox
Also, according to this post, you have to register your validate command using the .register method on your Tk object. That is, add the line: text_only_Command = win.register(text_only)
, and call text_only_Command
instead of text_only
.
Finally, you have to pack your widget (so you need to create a Combobox object and then use the method .pack()
on it)
Altogether, your code should look like this:
import tkinter
# from tkinter import ttk
import re
win = tkinter.Tk()
def num_only(num):
if str.isdecimal(num): return True
elif num=="": return True
else: return False
def text_only(txt):
if re.match("^[a-z]$",txt.lower()): return True
elif re.match("^[أ-ي]$",txt): return True
elif txt == "": return True
else: return False
text_only_Command = win.register(text_only)
num_only_Command = win.register(num_only)
combo = tkinter.ttk.Combobox(win, font="none 12 bold", validate="key",
validatecommand=(text_only_Command ,"%P"),
values=("value1","value2","value3","value4"))
combo.pack()
win.mainloop()