尝试使用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()
答案 0 :(得分:3)
在上一行(lblresult = ...
)上,您忘记关闭已打开的括号。 Python将此(将该行和下一行btresult = ...
)解释为一整行代码,但显然这不适用于您的代码,因此SyntaxError
答案 1 :(得分: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()