Class 将自类Tkinter条目数据发送到其作用域之外的函数
我设置了两个输入框,目标是按下一个按钮,并使用范围外的函数对输入的数字应用某种类型的数学。(我省略了包装和框架代码,因为我认为这与问题无关。) 我曾想过将条目设置为全局范围,但这会阻止我对其进行访问吗?我认为当终端用户将数字输入到输入框中时,有一种方法可以让事件运行get,因为ktinker文档中提到它“需要更多解释”。我不确定这样做的最佳方式是什么,我的研究得出了相互矛盾的答案Class 将自类Tkinter条目数据发送到其作用域之外的函数,class,function,python-3.x,scope,tkinter,Class,Function,Python 3.x,Scope,Tkinter,我设置了两个输入框,目标是按下一个按钮,并使用范围外的函数对输入的数字应用某种类型的数学。(我省略了包装和框架代码,因为我认为这与问题无关。) 我曾想过将条目设置为全局范围,但这会阻止我对其进行访问吗?我认为当终端用户将数字输入到输入框中时,有一种方法可以让事件运行get,因为ktinker文档中提到它“需要更多解释”。我不确定这样做的最佳方式是什么,我的研究得出了相互矛盾的答案 谢谢 让您的按钮调用类上的方法,并让该方法调用doMathFUnction,将值传递给它。这样做意味着您的doMat
谢谢 让您的按钮调用类上的方法,并让该方法调用
doMathFUnction
,将值传递给它。这样做意味着您的doMathFunc
函数不需要了解任何有关GUI内部工作的信息
class class1:
def __init__(self):
...
self.calcButton = tkinter.Button(..., command=self.doCalc)
def doCalc(self):
a = self.entry1.get()
b = self.entty2.get()
doMathFunction(a,b)
如果doMathFunction的超出范围,则可以使用lambda语句并向doMathFunction添加变量
class class1:
def __init__(self):
self.entry1= tkinter.Entry(self.uframe, width=10)
self.entry2= tkinter.Entry(self.uframe, width=10)
self.calcButton = tkinter.Button(self.frame, text="Submit", command = \
lambda e1 = self.entry1.get(), e2 = self.entry2.get(): doMathFunction(e1,e2))
def doMathFunction(e1, e2):
print(e1*e2) # Or whatever you were going to do
通常,在命令语句中使用函数的行为类似于变量声明,函数被执行,返回语句被分配给变量。但是,对于lambda,它后面的函数仅在调用时执行
因此,当按下calcButton并调用其命令语句时,将执行lambda“函数”(带有e1和e2)。这就像创建一个中间人函数来处理呼叫
class class1:
def __init__(self):
self.entry1= tkinter.Entry(self.uframe, width=10)
self.entry2= tkinter.Entry(self.uframe, width=10)
self.calcButton = tkinter.Button(..., command = self.middleman)
def middleman(self):
e1 = self.entry1.get()
e2 = self.entry2.get()
doMathFunction(e1, e2)
def doMathFunction(e1, e2):
print(e1*e2) # Or whatever you were going to do
class class1:
def __init__(self):
self.entry1= tkinter.Entry(self.uframe, width=10)
self.entry2= tkinter.Entry(self.uframe, width=10)
self.calcButton = tkinter.Button(..., command = self.middleman)
def middleman(self):
e1 = self.entry1.get()
e2 = self.entry2.get()
doMathFunction(e1, e2)
def doMathFunction(e1, e2):
print(e1*e2) # Or whatever you were going to do