使用Python GUI添加整数时遇到麻烦

时间:2018-11-22 01:27:02

标签: python user-interface

过去4个月来我一直在学习Python,目前正在学习GUI应用程序。我在尝试使用CheckBox选择整数后尝试添加整数时遇到麻烦。整数确实相加,但是我得到了这些疯狂的结果。

这是我的代码:

def Calculate(self):
        self.message = "Your total charge = $"

        chargeTotal = 0

        if self.checkBoxVar1.get() == 1:
            chargeTotal += 30
            self.message +=  str(chargeTotal)

        if self.checkBoxVar2.get() == 1:
            chargeTotal += 20
            self.message += str(chargeTotal)

        if self.checkBoxVar3.get() == 1:
            chargeTotal +=  40
            self.message += str(chargeTotal)

        if self.checkBoxVar4.get() == 1:
            chargeTotal +=  100
            self.message += str(chargeTotal)

        if self.checkBoxVar5.get() == 1:
            chargeTotal +=  35
            self.message += str(chargeTotal)

        if self.checkBoxVar6.get() == 1:
            chargeTotal +=  200
            self.message += str(chargeTotal)

        if self.checkBoxVar7.get() == 1:
            chargeTotal += 20
            self.message += str(chargeTotal)

        tkinter.messagebox.showinfo("Total Charges", self.message)

这是我不断得到的疯狂结果: https://imgur.com/a/qwIpTrn

我知道它必须是一个简单的解决方案,但我对Python还是很陌生,似乎无法弄清楚

2 个答案:

答案 0 :(得分:0)

您需要删除每个self.message += str(chargeTotal)语句中的if,然后将其放入下面的代码中。希望对您有所帮助。

def Calculate(self):
    self.message = "Your total charge = $"

    chargeTotal = 0

    if self.checkBoxVar1.get() == 1:
        chargeTotal += 30

    if self.checkBoxVar2.get() == 1:
        chargeTotal += 20

    if self.checkBoxVar3.get() == 1:
        chargeTotal +=  40

    if self.checkBoxVar4.get() == 1:
        chargeTotal +=  100

    if self.checkBoxVar5.get() == 1:
        chargeTotal +=  35

    if self.checkBoxVar6.get() == 1:
        chargeTotal +=  200

    if self.checkBoxVar7.get() == 1:
        chargeTotal += 20

    self.message += str(chargeTotal)
    tkinter.messagebox.showinfo("Total Charges", self.message)

答案 1 :(得分:0)

您要做的是在对self.message的每个if语句中,将转换为字符串的数字连接起来。

例如如果输入前两个if语句,则首先会得到“您的总费用= $ 30”,然后,得到“您的总费用= $ 3020”

相反,您应该最后一次将chargeTotal添加到self.message中:

def Calculate(self):
    self.message = "Your total charge = $"

    chargeTotal = 0

    if self.checkBoxVar1.get() == 1:
        chargeTotal += 30

    if self.checkBoxVar2.get() == 1:
        chargeTotal += 20

    if self.checkBoxVar3.get() == 1:
        chargeTotal += 40

    if self.checkBoxVar4.get() == 1:
        chargeTotal += 100

    if self.checkBoxVar5.get() == 1:
        chargeTotal += 35

    if self.checkBoxVar6.get() == 1:
        chargeTotal += 200

    if self.checkBoxVar7.get() == 1:
        chargeTotal += 20

    self.message += str(chargeTotal)
    tkinter.messagebox.showinfo("Total Charges", self.message)