如何导入这些功能?属性错误



我刚开始学习python,并使用python和tkinter创建了一个简单的计算器GUI。按钮有效,但由于某种原因,当我尝试将函数移动到另一个文件并导入它们时,它不起作用,并且出现 AttributeError。

主文件:

from tkinter import *
from functions_calc_advanced import *
if _name_ == "_main_":
gui = Tk()
gui.configure(background="white")
gui.title("LABINF Calculator WSS2018")
gui.geometry("400x200")
equation = StringVar()
expression_field = Entry(gui, textvariable=equation)
expression_field.grid(columnspan=4, ipadx=10)
equation.set('enter your expression')

窗口打开,但当我按下任何按钮时,我收到错误。此按钮1只是一个示例,所有其他按钮的结构都相同

button1 = Button(gui, text=' 1 ',command=lambda: press(1), height=1, width=7)
button1.grid(row=4, column=0)
buttonauf = Button(gui, text=' ( ', fg='black', bg='grey',command=lambda: press('('), height=1, width=7)
buttonauf.grid(row=5, column=0)
buttonzu = Button(gui, text=' ) ', fg='black', bg='grey',command=lambda: press(')'), height=1, width=7)
buttonzu.grid(row=6, column=0)
buttondot = Button(gui, text=' . ', fg='black', bg='grey',command=lambda: press('.'), height=1, width=7)
buttondot.grid(row=5, column=2)
buttonquit = Button(gui, text="Quit", command = gui.destroy, bg = 'black', fg = "white")
buttonquit.grid(row = 0, column = 4)

计算按钮

plus = Button(gui, text=' + ', fg='orange', bg='white', command=lambda: press("+"), height=1, width=2)
plus.grid(row=2, column=3)
minus = Button(gui, text=' - ', fg='orange', bg='white', command=lambda: press("-"), height=1, width=2)
minus.grid(row=3, column=3)
mult = Button(gui, text=' * ', fg='orange', bg='white', command=lambda: press("*"), height=1, width=2)
mult.grid(row=4, column=3)
div = Button(gui, text=' / ', fg='orange', bg='white', command=lambda: press("/"), height=1, width=2)
div.grid(row=5, column=3)
equal = Button(gui, text=' = ', fg='white', bg='orange', command=equalpress, height=1, width=7)
equal.grid(row=6, column=3)
clear = Button(gui, text='C', fg='white', bg='black', command=clear, height=1, width=7)
clear.grid(row=0, column=3)
gui.mainloop()

我尝试从中导入的函数文件:

expression = ""
equation = ""
def press(num):
global expression
expression = expression + str(num)
equation.set(expression)
def equalpress():
try:
global expression
total = str(eval(expression))
equation.set(total)
expression = ""
except: 
equation.set(" error ")
expression = ""
def clear():
global expression
expression = ""
equation.set("")

字符串没有set属性,因此您应该将尝试导入的函数文件更改为以下代码:

expression = ""
equation = ""
def press(num):
global expression, equation
expression = expression + str(num)
equation = expression
def equalpress():
global expression, equation
try:
total = str(eval(expression))
equation = total
expression = ""
except: 
equation = " error "
expression = ""
def clear():
global expression, equation
expression = ""
equation = ""

应将equation.set更改为equation = "..."str因为类型没有set属性

最新更新