如何创建一个 GUI 以将不同的两个复选框中的两个数字相加


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(( 中的值并进行加法

我尝试通过几种方式做到这一点,但我不明白如何使复选框为真/在选中该框时被选中,结果即使未选中这些框,代码也会显示答案

谢谢

如果我

理解正确,这是程序的简化版本,应该可以回答您的问题:

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 文档。 下面是将 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()

最新更新