这是有问题的代码。
for files in os.listdir('./apps'):
if files.endswith(".py"):
imported = importlib.import_module(files[:-3])
i=tk.Button(root,text=imported.MainWindow.buttonname,command=imported.MainWindow)
在这段代码中,我正在遍历一个名为apps的目录,对于该目录中的每个.py文件,我都需要将其导入,并调用一个名为mainWindow的类(每个.py文件都有一个mainWindow类),但是却出现此错误。
module 'test' has no attribute 'mainWindow'
class MainWindow():
def __init__(self):
self.window = tk.Toplevel
self.window.geometry('500x500')
这是我在test.py中的mainWindow类
更新 我尝试过
importedmainclass = importlib.import_module(imported.MainWindow)
仍然出现错误。
任何帮助将不胜感激!
答案 0 :(得分:1)
您的test.py使用MainWindow
,而代码在倒数第二行使用.mainWindow
。解决这个问题,它应该可以工作,或者至少会引发其他错误:-)。
答案 1 :(得分:1)
尝试执行此操作:
func()
并在目录./apps中添加文件importedmainclass = getattr(importlib.import_module(imported.__name__), 'MainWindow')
,例如:
__init__.py