我想创建带有多个条目窗口小部件的tkinter应用程序。我正在使用for循环创建小部件,打包小部件等。最后,我想使用tkinter跟踪方法来验证每个输入小部件的用户输入。如何使用for循环将相同的回调函数绑定到多个tkinter变量?我知道trace方法将为回调函数提供三个参数名称,索引和模式。例如,是否有任何方法可以使用名称参数作为该for循环中每个变量的唯一标识符?
这是我的代码:
import tkinter as tk
class EntryFormular(tk.Frame):
def __init__(self,master):
tk.Frame.__init__(self,master)
self.entrylist = [
"entry 1",
"entry 2",
"entry 3"
]
self.inputvars = list()
self.build()
def build(self):
for entry in self.entrylist:
var = tk.StringVar(self.master)
var.trace("w",self.validateFloatInput)
element = tk.Entry(self,textvariable=var)
element.pack()
self.inputvars.append(var)
def validateFloatInput(self,name,index,mode):
# bind this method to all 3 entry widgets
# get variable content using .get() method
# only allow float inputs between 0 and 1, such as 1.0 or 0.85
pass
class Application:
def __init__(self, master):
self.master = master
self.entryformular = EntryFormular(master)
self.entryformular.pack()
if __name__ == "__main__":
root = tk.Tk()
my_gui = Application(root)
root.mainloop()
答案 0 :(得分:0)
感谢杰森哈珀!那解决了我的问题。
这是我的代码:
import tkinter as tk
import re
class EntryFormular(tk.Frame):
def __init__(self,master):
tk.Frame.__init__(self,master)
self.entrylist = [
"entry 1",
"entry 2",
"entry 3"
]
self.inputvars = list()
self.build()
def build(self):
for entry in self.entrylist:
var = tk.StringVar(self.master)
var.trace("w",self.validateFloatInput)
element = tk.Entry(self,textvariable=var)
element.pack()
self.inputvars.append(var)
def validateFloatInput(self,name,index,mode):
regex = re.compile(r'^0(\.\d+)?|1(\.0?)?$')
for var in self.inputvars:
if name == str(var):
if regex.match(var.get()):
pass
else:
var.set(var.get()[:-1])
self.master.bell()
class Application:
def __init__(self, master):
self.master = master
self.entryformular = EntryFormular(master)
self.entryformular.pack()
if __name__ == "__main__":
root = tk.Tk()
my_gui = Application(root)
root.mainloop()