我有三个文件,我正在尝试通过单选按钮更改变量的值:配置文件epoch=1图像分类器.pyimport configtrain(args, model, device, train_loader, optimizer, config.epoch)图形用户界面import configdef changeEpoch(epochValue): config.epoch=epochValuevar1 = 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,我似乎无法弄清楚为什么。
1 回答
函数式编程
TA贡献1807条经验 获得超9个赞
考虑这行代码:
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))
添加回答
举报
0/150
提交
取消