0

尝试用 python 和 tkinter 制作一个非常基本的加法计算器。它给了我一个错误:

    btresult = Button(window, text = "Compute Sum", command = self.result).grid(row = 4, column = 2, sticky = E)
           ^
SyntaxError: invalid syntax

我无法弄清楚如何连接它。

from tkinter import *

class addCalculator:
    def __init__(self):
        window = Tk()
        window.title("Add Calculator")

        Label(window, text = "First Number: ").grid(row = 1, column = 1, sticky = W)
        Label(window, text = "Second Number: ").grid(row = 2, column = 1, sticky = W)

        self.number1Var = StringVar()
        Entry(window, textvariable = self.number1Var, justify = RIGHT).grid(row = 1, column = 2)

        self.number2Var = StringVar()
        Entry(window, textvariable = self.number2Var, justify = RIGHT).grid(row = 2, column = 2)

        self.resultVar = StringVar()
        lblresult = Label(window, textvariable = self.result.grid(row = 3, column = 2, sticky = E)

        btresult = Button(window, text = "Compute Sum", command = self.result).grid(row = 4, column = 2, sticky = E)

        def result(self):
            resultVar = self.resultVar.set(eval(self.number1Var.get()) + eval(self.number2Var.get()))
            return resultVar

        window.mainloop()

addCalculator()
4

2 回答 2

3

在上一行 ( lblresult = ...) 中,您忘记关闭打开的括号。Python 将其(该行和下一行btresult = ...)解释为一整行代码,但显然这不适用于您的代码,因此SyntaxError

于 2013-09-20T00:48:11.230 回答
0

我以自己的方式解决了这个问题。我试图忠实于原始问题,但代码需要大量清理。有很多小问题需要解决,但我认为主要问题是将整数传递给函数的方法。我还将原来的 lblresult 从标签更改为 Entry 小部件。我仍然是 Python 的新手,但正在变得更好。我在寻找类似答案时发现了这个问题,解决这个问题也解决了我的问题。谢谢!下面的代码:

from Tkinter import *

class addCalculator:
    def __init__(self):
        window = Tk()
        window.title("Add Calculator")

        def result(z1,z2):
            biz=z1+z2
            lblresult.delete(0,END)
            lblresult.insert(0,biz)
            return

        Label1 = Label(window, text = "First Number: ").grid(row = 1, column = 1, sticky = W)
        Label2 = Label(window, text = "Second Number: ").grid(row = 2, column = 1, sticky = W)

        self.number1Var = IntVar()
        Entry1 = Entry(window, textvariable = self.number1Var, justify = RIGHT).grid(row = 1, column = 2)

        self.number2Var = IntVar()
        Entry2 = Entry(window, textvariable = self.number2Var, justify = RIGHT).grid(row = 2, column = 2)

        Label3 = Label(window, text = "Result: ").grid(row = 3, column = 1, sticky = W)

        lblresult = Entry(window, justify = RIGHT)
        lblresult.grid(row = 3, column = 2, sticky = E)

        btresult = Button(window,text="Compute Sum",command=lambda:result(self.number1Var.get(),self.number2Var.get()))
        btresult.grid(row = 4, column = 2, sticky = E)

        window.mainloop()

addCalculator()
于 2016-04-19T16:57:45.603 回答