[英]How to use tkinter as ttk
I am working on a big programme and I want Combobox to accept text only to be entered in it我正在开发一个大程序,我希望 Combobox 接受只能在其中输入的文本
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验证不起作用,但它与 tk.Entry 一起使用
ttk is a module of tkinter, so you have to import it like this: ttk是tkinter的一个模块,所以要这样导入:
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或者不调用ttk.Combobox
(注意 python 区分大小写,因此调用ttk.combobox
将不起作用),您可以这样调用它
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
.此外,根据这篇文章,您必须在 Tk object 上使用 .register 方法注册您的验证命令。也就是说,添加以下行: text_only_Command = win.register(text_only)
,并调用text_only_Command
而不是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)最后,你必须打包你的小部件(所以你需要创建一个 Combobox object 然后在上面使用方法.pack()
)
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.