我有一个Tk应用程序,它有几个数字输入的输入框:
self.entry = Tkinter.Entry(self, textvariable = self.c2_low).grid(column=0,row=2, sticky ='W')
self.entry = Tkinter.Entry(self, textvariable = self.c2_high).grid(column=1,row=2,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.c3_low).grid(column=0,row=3,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.c3_high).grid(column=1,row=3,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.ic4_low).grid(column=0,row=4,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.ic4_high).grid(column=1,row=4,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.nc4_low).grid(column=0,row=5,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.nc4_high).grid(column=1,row=5,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.ic5_low).grid(column=0,row=6,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.ic5_high).grid(column=1,row=6,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.nc5_low).grid(column=0,row=7,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.nc5_high).grid(column=1,row=7,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.n2_low).grid(column=0,row=9,sticky='W')
self.entry = Tkinter.Entry(self, textvariable = self.n2_high).grid(column=1,row=9,sticky='W')
这完全正常,我可以在其他功能中使用数字输入。但是,我想要一个单独的函数,当一个'用通用数字填充时,用函数指定的通用数字填充那些输入框。单击按钮。这可能吗?
编辑:我有一个按钮用于对所提到的那些数字进行通用模拟,但是我喜欢输入框来显示我指定的数字。答案 0 :(得分:2)
Entry小部件的内容直接链接到其控制变量,因此调用相应StringVar上的.set()方法将设置条目的内容
self.c2_low.set("c2_low")
self.c2_high.set(23) #gets converted to a str automatically
然后获取内容返回使用相同变量的.get()方法:
try:
x = int( self.c2_low.get() )
except ValueError:
NotImplemented #handle invalid input
你也在新创建的Entries上调用.grid()方法,因为.grid()返回None,因此稍后会丢失对它们的引用,使用一个简单的类将textvariable与条目小部件:
class Smart_entry(Tkinter.Entry):
def __init__(self,master,column,row,content="",name=None):
self.textvar = Tkinter.StringVar(master,content,name)
Tkinter.Entry.__init__(self,master,textvariable=self.textvar)
self.grid(column=column, row=row, sticky="W")
def get(self):
return self.textvar.get()
def set(self,value):
return self.textvar.set(value)
# if all the entries are int/float
# then handling the conversion in the .get() may be useful
## def get(self,conv=str):
## "returns content after converting to specified type, returns None if conversion failed"
## try:
## return conv( self.textvar.get() )
## except ValueError:
## return None