2

我已经开始在一个 GUI 系统上工作,我需要从一个文件中导入一个函数,以便在按下按钮时在主文件中执行,但是每次运行它时,我都会得到:

AttributeError: partially initialized module 'Two' has no attribute 'sum'
  (most likely due to a circular import)

程序应该输入两个值,Value_aValue_b,被调用的函数应该将这两个值sum()相加并在新窗口中输出结果。这是我要导入的文件及其功能的示例sum()

Two.py

from tkinter import *  #Import the tkinter module    
import One #This is the main file, One.py

def sum():
    newWindow = Toplevel(One.Window)
    newWindow.title("Sum")
    a = int(One.Value_a.get())
    b = int(One.Value_b.get())
    c = a+b
    Label(newWindow, text= str(c)).grid(row=1, column=0)

这是主文件的样子:

One.py

from tkinter import *
import Two

Window = Tk()
Window.title("Main Window")

Value_a = Entry(Window, width=15).grid(row=1, column=0)
Value_b = Entry(Window, width=15).grid(row=2, column=0)
my_button = Button(Window, text="Test", command=lambda: Two.sum).grid(row=3, column=0)

Window.mainloop()

当它运行时,我最终得到上述错误。

4

2 回答 2

2

问题是因为你确实有一个循环import。模块One导入模块Two,模块导入模块One......等等。但是,@acw1668 建议的简单修复不足以解决问题,因为Two模块引用的不仅仅是模块的Window属性One。我的解决方案将模块One中的函数Two作为参数传递模块中的东西(因此Two模块不需要import它来访问它们)。

问题Tkinter: AttributeError: NoneType object has no attribute讨论了您的 tkinter 代码的另一个问题 ,我建议您阅读。

以下是解决所有这些问题的两个模块的更改。

One.py

from tkinter import *
import Two


Window = Tk()
Window.title("Main Window")

Value_a = Entry(Window, width=15)
Value_a.grid(row=1, column=0)
Value_b = Entry(Window, width=15)
Value_b.grid(row=2, column=0)

my_button = Button(Window, text="Test",
                   command=lambda: Two.sum(Window, Value_a, Value_b))
my_button.grid(row=3, column=0)

Window.mainloop()

Two.py

from tkinter import *


def sum(Window, Value_a, Value_b):
    newWindow = Toplevel(Window)
    newWindow.title("Sum")
    a = int(Value_a.get())
    b = int(Value_b.get())
    c = a+b
    Label(newWindow, text= str(c)).grid(row=1, column=0)
于 2021-03-19T07:19:55.763 回答
0

(这是另一个答案,与我最初在其他答案中的答案非常相似,然后再做一些我觉得更简单的事情。我将其作为单独的答案发布,因为事实证明模块获取自身引用的想法是很长一段时间,所以这样做并不像我最初想象的那么奇怪或那么骇人听闻。)

问题是因为你确实有一个循环import。模块One导入模块Two,模块导入模块One......等等。但是,@acw1668 建议的简单修复不足以解决问题,因为Two模块引用的不仅仅是模块的Window属性One。我的解决方案将整个 One模块作为参数传递给函数(因此Two模块不需要import它来访问其属性)。

问题Tkinter: AttributeError: NoneType object has no attribute讨论了您的 tkinter 代码的另一个问题 ,我建议您阅读。

以下是解决所有这些问题的两个模块的更改。为了避免循环导入,Button 命令现在将调用模块作为参数传递给模块中的sum()函数Two。虽然做这样事情有点不寻常,但如果你仔细想想,实际上是非常合乎逻辑的(并且希望避免循环导入)。

One.py

from tkinter import *
import Two

CURRENT_MODULE = __import__(__name__)

Window = Tk()
Window.title("Main Window")

Value_a = Entry(Window, width=15)
Value_a.grid(row=1, column=0)
Value_b = Entry(Window, width=15)
Value_b.grid(row=2, column=0)

my_button = Button(Window, text="Test", command=lambda: Two.sum(CURRENT_MODULE))
my_button.grid(row=3, column=0)

Window.mainloop()

Two.py

from tkinter import *

def sum(One):
    newWindow = Toplevel(One.Window)
    newWindow.title("Sum")
    a = int(One.Value_a.get())
    b = int(One.Value_b.get())
    c = a+b
    Label(newWindow, text= str(c)).grid(row=1, column=0)
于 2021-03-19T17:13:36.270 回答