from tkinter import *
from ProjectHeader import *
def sel1():
return 1
def sel2():
return 2
def sel3():
return 3
def sel4():
return 4
def sel():
selection = "THe answer is: " + str(sel2() + sel3())
label.config(text = selection)
top = Tk()
var = IntVar()
CheckVar1 = sel1()
CheckVar2 = sel2()
CheckVar3 = sel3()
CheckVar4 = sel4()
C1 = Checkbutton(top, text = "Option1", variable = CheckVar1)
C2 = Checkbutton(top, text = "Option2", variable = CheckVar2)
C3 = Checkbutton(top, text = "Option3", variable = CheckVar3)
C4 = Checkbutton(top, text = "Option4", variable = CheckVar4)
B = Button(top, text ="ADD", command=sel)
B.pack()
C1.pack()
C2.pack()
C3.pack()
C4.pack()
label = Label(top)
label.pack()
top.mainloop()
正如标题所说,如何创建一个GUI来从不同的两个复选框中添加两个数字?
例如,当我检查选项2和选项3时,程序将获得sel2()和sel3()中的值并进行添加
我试过以某种方式做到这一点,但是当我选中框时,我不明白如何使复选框成为真/选择,结果代码显示答案,即使框中也是如此未经检查
感谢
答案 0 :(得分:3)
以下是您的程序的简化版本,如果我理解正确的话,它应该回答您的问题:
from Tkinter import *
gui = Tk()
#create variables to store check state
checked1 = IntVar()
checked2 = IntVar()
#create values for the two boxes
cb1 = 5
cb2 = 10
#create a callback for our button
def callback():
print(checked1.get()*cb1+checked2.get()*cb2)
c1 = Checkbutton(gui, text='b1', variable=checked1)
c2 = Checkbutton(gui, text='b2', variable=checked2)
b1 = Button(gui, text="ADD", command=callback)
c1.pack()
c2.pack()
b1.pack()
gui.mainloop()
您的程序中达到了复杂程度,将您的gui重组为一个类是有益的。如果您想要如何执行此操作的示例,请阅读Tkinter documentation。以下是GUI作为自定义类的示例:
from Tkinter import *
class Gui(object):
def __init__(self, parent):
self.top = parent
self.checked1 = IntVar()
self.checked2 = IntVar()
self.c1_value = 1
self.c2_value = 2
self.c1 = Checkbutton(self.top, text='b1', variable=self.checked1)
self.c2 = Checkbutton(self.top, text='b2', variable=self.checked2)
self.b1 = Button(self.top, text="ADD", command=self.callback)
self.l1 = Label(self.top)
self.c1.pack()
self.c2.pack()
self.b1.pack()
self.l1.pack()
def callback(self):
value = self.c1_value*self.checked1.get() + self.c2_value*self.checked2.get()
self.l1.config(text=str(value))
root = Tk()
my_window = Gui(root)
root.mainloop()