功能无法打印正确的输出

时间:2019-07-04 14:35:45

标签: python-3.x if-statement tkinter

我编写了一个带有复选框的小型应用程序,因此当我标记一个或两个复选框时,它应该打印一个特定的变量,但是问题出在这里,当我标记两个复选框时,我没有得到输出我想要。谢谢

from tkinter import *
class STproject():

    def __init__(self,app):

        self.CheckVar1 =IntVar()
        self.CheckVar2 =IntVar()

        self.button=Button(app,text='PRINT',command=lambda:self.functionality())
        self.button.grid(row=0,column=0)
        self.Lidbox=Checkbutton(app,variable=self.CheckVar1,onvalue=1,
                           offvalue=0)
        self.Lidbox.grid(row=1,column=0)
        self.Seperatorbox=Checkbutton(app,variable=self.CheckVar2,onvalue=1,
                           offvalue=0)
        self.Seperatorbox.grid(row=1,column=1)

    def functionality(self):
        if self.CheckVar1.get():
            print('first')
        elif self.CheckVar2.get():
            print('2nd part')
        elif self.CheckVar1.get() and self.CheckVar2.get():
            print('3rd part')
        else:
            print('4th part')

root=Tk()
root.title('SteelBox Inc. Calculator')
application=STproject(root) #2
root.mainloop() #3

1 个答案:

答案 0 :(得分:1)

如果同时选中了两个复选框,则第一个if将被评估为True,因为确实选中了self.CheckVar1。然后,其他elif语句将不会被评估。

将代码更改为:

def functionality(self):
    if self.CheckVar1.get() and self.CheckVar2.get():
        print('3rd part')
    elif self.CheckVar1.get():
        print('first')
    elif self.CheckVar2.get():
        print('2nd part')
    else:
        print('4th part')