我有三个文件,我正试图通过单选按钮更改变量的值:
配置py
epoch=1
imageClassifier.py
import config
train(args, model, device, train_loader, optimizer, config.epoch)
GUI.py
import config
def changeEpoch(epochValue):
config.epoch=epochValue
var1 = IntVar()
epochRadioButton1 = Radiobutton(middleFrame, variable=var1, value=1,
text="1", command=changeEpoch(1))
epochRadioButton5 = Radiobutton(middleFrame, variable=var1, value=2,
text="5", command=changeEpoch(5))
epochRadioButton10 = Radiobutton(middleFrame, variable=var1, value=3,
text="10", command=changeEpoch(10))
epochRadioButton20 = Radiobutton(middleFrame, variable=var1, value=4,
text="20", command=changeEpoch(20))
var1.set(1)
然而,不管怎样,当我运行程序时,epoch的值总是20,我似乎不知道为什么。
考虑这行代码:
epochRadioButton20 = Radiobutton(..., command=changeEpoch(20))
它的效果与此完全相同:
result = changeEpoch(20)
epochRadioButton20 = Radiobutton(..., command=result)
command
属性采用可调用。但是,您的代码会立即调用该函数,并将结果提供给command
属性。
我建议让函数从单选按钮获取值,而不是将新值传递给函数。为此,请进行以下更改:
def changeEpoch():
epochValue = var1.get()
config.epoch=epochValue
...
epochRadioButton20 = Radiobutton(..., command=lambda: changeEpoch)
另一种解决方案是使用lambda
创建一个匿名函数,该函数调用changeEpoch
(假设未修改changeEpoch
(:
epochRadioButton20 = Radiobutton(..., command=lambda: changeEpoch(20))