【发布时间】:2021-03-19 06:05:41
【问题描述】:
我已经开始在一个 GUI 系统上工作,我需要从一个文件中导入一个函数,以便在按下按钮时在主文件中执行,但每次运行它都会得到:
AttributeError: partially initialized module 'Two' has no attribute 'sum'
(most likely due to a circular import)
程序应该输入两个值,Value_a 和Value_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()
运行时,我最终得到了上述错误。
【问题讨论】:
-
在
Two.py中导入One将创建Tk(One.Window) 的另一个实例,而不是在运行Tk(Window) 的实例时使用One.py。您需要将Window、Value_a和Value_b传递给Two.sum(),并且不要在Two.py中导入One。 -
@acw1668:没那么容易。请参阅我发布的答案。
标签: python tkinter tkinter-button